public class b {
public static void main(String[] args) {
byte b = 1;
long l = 127;
// b = b + l; // 1 if I try this then it does not compile
b += l; // 2 if I try this then it does compile
System.out.println(b);
}
}
I am using this code but I have problem:
I don't understand why b=b+l; is not compiling but if I write b+=l; then it compiles and runs.
Please explain why this happens.
Hi I was wondering if someone could help me with this problem.
Thanks!!
Show how to use a stack S and a queue Q to generate all possible subsets of a set nonrecursively.
Hello,
what behaviour can I expect when I run this code:
do while(testA) {
// do stuff
} while(testB);
Will it behave like:
do {
while(testA) {
// do stuff
}
} while(testB);
Or:
if(testA) {
do {
// do stuff
} while(testA && testB);
}
Or something totally unexpected?
I ask this question because I think this is quite ambiguous, and for other people searching on this topic, not because I am lazy to test it out.
about = new JMenuItem("About");
about.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A((Toolkit.getDefaultToolkit().getMenuShortcutMask()))));
JMenu help = new JMenu("Help");
help.add(about);
I was wondering why my aaccelerators were not working. I am running this in snow leopard with JavaSe-1.6 VM. They do work if I pull the menu down then try the key sequence. Thanks
I know this question has be asked before generic comes out. Array does win out a bit given Array enforces the return type, it's more type-safe.
But now, with latest JDK 7, every time when I design this type of APIs:
public String[] getElements(String type)
vs
public List<String> getElements(String type)
I am always struggling to think of some good reasons to return A Collection over An Array or another way around. What's the best practice when it comes to the case of choosing String[] or List as the API's return type? Or it's courses for horses.
I don't have a special case in my mind, I am more looking for a generic pros/cons comparison.
I am trying to get the KeyListener working for Blackberry, but none of the Dialogs pop up indicating that a key has been pressed (see code below, each action has a dialog popup in them).
Any ideas on what i might be doing wrong?
public class CityInfo extends UiApplication implements KeyListener
{
static CityInfo application;
public static void main(String[] args)
{
//create a new instance of the application
//and start the application on the event thread
application.enterEventDispatcher();
}
public CityInfo()
{
//display a new screen
application = new CityInfo();
pushScreen(new WorkflowDisplayScreen());
this.addKeyListener(this);
}
public boolean keyChar(char arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
Dialog.alert("key pressed : " + arg0);
return true;
}
public boolean keyDown(int keycode, int time) {
// TODO Auto-generated method stub
Dialog.alert("keyDown : " + keycode);
return false;
}
public boolean keyRepeat(int keycode, int time) {
// TODO Auto-generated method stub
Dialog.alert("keyRepeat : " + keycode);
return false;
}
public boolean keyStatus(int keycode, int time) {
// TODO Auto-generated method stub
Dialog.alert("keyStatus : " + keycode);
return false;
}
public boolean keyUp(int keycode, int time) {
Dialog.alert("keyUp : " + keycode);
// TODO Auto-generated method stub
return false;
}
}
I also tried implementing keyChar on the MainScreen class but that did not yield any results either.
Is anybody out there using Project Lombok for a large scale production system? How does it influence your compile process (i.e. does it do two-pass compilation, slow it down, make it more fragile)?
I want a simple class that implements a fixed-size circular buffer. It should be efficient, easy on the eyes, generically typed.
EDIT: It need not be MT-capable, for now. I can always add a lock later, it won't be high-concurrency in any case.
Methods should be: .Add and I guess .List, where I retrieve all the entries. On second thought, Retrieval I think should be done via an indexer. At any moment I will want to be able to retrieve any element in the buffer by index. But keep in mind that from one moment to the next Element[n] may be different, as the Circular buffer fills up and rolls over.
This isn't a stack, it's a circular buffer. Regarding "overflow": I would expect internally there would be an array holding the items, and over time the head and tail of the buffer will rotate around that fixed array. But that should be invisible from the user. There should be no externally-detectable "overflow" event or behavior.
This is not a school assignment - it is most commonly going to be used for a MRU cache or a fixed-size transaction or event log.
Hy ,what i`m trying to do is something like this:
private class aClass
{
private ArrayList idProd;
aClass(ArrayList prd)
{
this.idProd=new ArrayList(prd);
}
public ArrayList getIdProd()
{
return this.idProd;
}
}
So if i have multiple instances of ArrayLIst (st1 ,st2 ,st3) and I want to make new objects of aClass :
{
aClass obj1,obj2,obj3;
obj1=new aClass(st1);
obj2=new aClass(st2);
obj3=new aClass(st3);
}why all of the aClass objects will return st3 if I access the method getIdProd() for each of them(obj1..obj3)? is an arraylist as a instance variable automatically declared static?
Hey I am trying to shift elements forward sending the last element in the array to data[0]. I did the opposite direction but I can't seem to find my mistake in going in this direction.
Pos is users inputed shift times amount
temp is the temporary holder.
data is the array
if(pos 0)
{
do
{
temp = data[data.length -1];
for(int i =0; i < data.length; i++)
{
if(i == data.length-1)
{
data[0] = temp;
}
else
{
data[i+1] = data[i];
}
}
pos--;
}while(pos > 0);
}
Thanks.
Hi all I have the following issue. I have a table of reserves in my MySQL DB, the date columns is defined DATETIME. I need to make a query using hibernate to find all reserves in one day no matter the hour, just that its the same year month and date, and I'm doing this
public List<Reserve> bringAllResByDate(Date date){
em = emf.createEntityManager();
Query q = em.createQuery("SELECT r FROM Reserve r WHERE r.date=:date ");
q.setParameter("date", date);
...
I really dont know how to make it compare, and bring me just those from the specified date, any help??
I need to upload a .csv file and save the records in bigtable.
My application successfully parse 200 the records in the csv files and save to table.
Here is my code to save the data.
for (int i=0;i<lines.length -1;i++) //lines hold total records in csv file
{
String line = lines[i];
//The record have 3 columns integer,integer,Text
if(line.length() > 15)
{
int n = line.indexOf(",");
if (n>0)
{
int ID = lInteger.parseInt(ine.substring(0,n));
int n1 = line.indexOf(",", n + 2);
if(n1 > n)
{
int Col1 = Integer.parseInt(line.substring(n + 1, n1));
String Col2 = line.substring(n1 + 1);
myTable uu = new myTable();
uu.setId(ID);
uu.setCol1(MobNo);
Text t = new Text(Col2);
uu.setCol2(t);
PersistenceManager pm = PMF.get().getPersistenceManager();
pm.makePersistent(uu);
pm.close();
}
}
}
}
But when no of records grow it gives timeout error.
The csv file may have upto 800 records.
Is it possible to do that in App-Engine?
(something like batch update)
If I have a try/catch block with returns inside it, will the finally block be called?
For example:
try {
something();
return success;
}
catch (Exception e) {
return failure;
}
finally {
System.out.println "i don't know if this will get printed out."
}
I know I can just type this in an see what happens (which is what I'm about to do, actually) but when I googled for answers nothing came up, so I figured I'd throw this up as a question.
Thanks!
I'm trying to zip a large number of pdf files (stored as BLOBs in the DB) and then return the zip as an attachment to the user.
What's the best way to do this without running into memory issues?
Another note: I actually need to merge some PDFs prior to adding them to the ZipOutputStream. Therefore, a couple PDFs will need to be stored in memory at a time.
I assume it would be best to then store them as temporary files on the server before zipping them all?
Consider this line:
if (object.getAttribute("someAttr").equals("true")) { // ....
Obviously this line is a potential bug, the attribute might be null and we will get a NullPointerException. So we need to refactor it to one of two choices:
First option:
if ("true".equals(object.getAttribute("someAttr"))) { // ....
Second option:
String attr = object.getAttribute("someAttr");
if (attr != null) {
if (attr.equals("true")) { // ....
The first option is awkward to read but more concise, while the second one is clear in intent, but verbose.
Which option do you prefer in terms of readability?
I want to create a program for generating the series for the given base-n. ,
for example if my input is 2,then series shuould be, 00,01,10,11,etc.,(binary)
if my input is 10,then series shuould be,1,2,3,4,5,etc.,(decimal)
is there any general mechanism to find these numbers so that I can program for base-n.,
This is my xml file.
- <deviceparameters>
- <parameter componenttype="TextBox">
<name>Operating Type</name>
<oid>1.3.6.1.4.1.31163.5.1.1</oid>
<writable>true</writable>
<description>The operating type defines which waveform type is used. This configuration takes several seconds to execute</description>
- <paramvalues type="Integer">
<value default="No">123</value>
</paramvalues>
</parameter>
- <parameter componenttype="TextBox">
<name>Active Waveform Status</name>
<oid>1.3.6.1.4.1.31163.5.1.2</oid>
<writable>false</writable>
<description>Show the status of the waveform configured by operatingType</description>
- <paramvalues type="String">
<value default="yes">Active</value>
</paramvalues>
</parameter>
</deviceparameters>
I want to remove node with name 'Active wavwform Status'. How can I reomve that particular node from xml.
The code I have written is below.
rootElement = doc.getDocumentElement();
NodeList nList = doc.getElementsByTagName("parameter");
String nodeName = TF_name.getText();
System.out.println(""+nList.getLength());
for (int temp = 0; temp < nList.getLength();temp++)
{
Node nNode = nList.item(temp);
Element eElement = (Element) nNode;
String upname1 = getTagValue("name", eElement);
if(upname1.equals(nodeName))
{
System.out.println("Parent: "+nNode.getParentNode().getNodeName());
System.out.println("nodename: "+nNode.getNodeName());
System.out.println("rmoving ....");
rootElement.removeChild(nNode);
System.out.println("removed...");
}
}
Hello guys,
One thing I want to know is how to calculate what date will it be 10 days from today.
Second thing is to check if one Date is between two other Dates.
For example, let's say I have an app that shows what events I need to do in the next 10 days (planner). Now how can I see if the date I assigned to an event is between today and the date that is 10 days from today?
This is my code...
class info{
public static void main (String[]args) throws IOException{
char gen;
while(true) { //problem occurs with this while
System.out.print("\nENTER YOUR GENDER (M/F) : ");
gen=(char)System.in.read();
if(gen=='M' || gen=='F' || gen=='m' || gen=='f'){
break;
}
}
System.out.println("\nGENDER = "+gen);
}
}
This is my output...
ENTER YOUR GENDER (M/F) : h
ENTER YOUR GENDER (M/F) :
ENTER YOUR GENDER (M/F) :
ENTER YOUR GENDER (M/F) : m
GENDER = m
Could someone please help me understand why it is asking for the gender so many times.
Im a bit unsure and have to get advice.
I have the:
public class MyApp extends JFrame{
And from there i do;
MyServer = new MyServer (this);
MyServer.execute();
MyServer is a:
public class MyServer extends SwingWorker<String, Object> {
MyServer is doing listen_socket.accept() in the doInBackground()
and on connection it create a new
class Connection implements Runnable {
I have the belove DbHelper that are a singleton.
It holds an Sqlite connected. Im initiating it in the above MyApp
and passing references all the way in to my runnable:
class Connection implements Runnable {
My question is what will happen if there are two simultaneous read or `write?
My thought here was the all methods in the singleton are synchronized and
would put all calls in the queue waiting to get a lock on the synchronized method.
Will this work or what can i change?
public final class DbHelper {
private boolean initalized = false;
private String HomePath = "";
private File DBFile;
private static final String SYSTEM_TABLE = "systemtable";
Connection con = null;
private Statement stmt;
private static final ContentProviderHelper instance = new ContentProviderHelper ();
public static ContentProviderHelper getInstance() {
return instance;
}
private DbHelper () {
if (!initalized)
{
initDB();
initalized = true;
}
}
private void initDB()
{
DBFile = locateDBFile();
try {
Class.forName("org.sqlite.JDBC");
// create a database connection
con = DriverManager.getConnection("jdbc:sqlite:J:/workspace/workComputer/user_ptpp");
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private File locateDBFile()
{
File f = null;
try{
HomePath = System.getProperty("user.dir");
System.out.println("HomePath: " + HomePath);
f = new File(HomePath + "/user_ptpp");
if (f.canRead())
return f;
else
{
boolean success = f.createNewFile();
if (success) {
System.out.println("File did not exist and was created " + HomePath);
// File did not exist and was created
} else {
System.out.println("File already exists " + HomePath);
// File already exists
}
}
} catch (IOException e) {
System.out.println("Maybe try a new directory. " + HomePath);
//Maybe try a new directory.
}
return f;
}
public String getHomePath()
{
return HomePath;
}
private synchronized String getDate(){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
public synchronized String getSelectedSystemTableColumn( String column) {
String query = "select "+ column + " from " + SYSTEM_TABLE ;
try {
stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String value = rs.getString(column);
if(value == null || value == "")
return "";
else
return value;
}
} catch (SQLException e ) {
e.printStackTrace();
return "";
} finally {
}
return "";
}
}
A JSpinner is used to store a number in my application (with a SpinnerNumberModel).
As expected, the spinner doesn't allow invalid characters (letters, symbols, etc.) to be stored. However, those characters do appear in the spinner component when I type them in. As soon as I switch the focus to another component, they disappear.
Is there a way to prevent invalid characters from appearing in the spinner?
Different websites are giving different opinions.
My understanding is this:
To clean up or reclaim the memory that an object occupies, the Garbage collector comes into action. (automatically is invoked???)
The garbage collector then dereferences the object. Sometimes, there is no way for the garbage collector to access the object. Then finalize is invoked to do a final clean up processing after which the garbage collector can be invoked.
is this right?
I have
public class QuantityType {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
@Persistent
private String type;
}
I am trying to setup a query to get the right QuantityType by it's key
gql = "select * from QuantityType where __key__='aght52oobW1hIHTWVzc2FnZRiyAQw'";
But its not working because
BadFilterError: BadFilterError: invalid filter: key filter value must be a Key; received aght52oobW1hIHTWVzc2FnZRiyAQw (a str).
I have also tried to use
gql = "select * from QuantityType where __key__=='" + KeyFactory.stringToKey(qTypeKey)+"'";
but it's now working..
How can I get a specific object from my datastore by it's key?