This question already has answers here:
Two ways to check if a list is empty - differences?
(4 answers)
Closed 3 years ago.
I do not have a way of really testing this without completely the other code I am working on but I just wanted to confirm this. If I am trying to code this statement:
If a node contains only positives, set decision to true.
If it contains only negatives set it to false
where pos is an ArrayList of all of the positive examples of a node and neg is othe same but with all of the negatives. Would this statement be valid?
if(!node.pos.isEmpty() && node.neg.isEmpty())
node.decision = true;
if(!node.neg.isEmpty() && node.pos.isEmpty())
node.decision = false;
So pretty much I am wondering if i put that the ArrayList is != null then does that mean that it must contain at least 1 thing and then when I put == null then that means it is empty?
No. An ArrayList is an object and will only be null if it hasn't been instantiated using the new keyword.
Use ArrayList.isEmpty() or ArrayList.size() > 0.
Related
This question already has answers here:
If statement executing all conditions
(9 answers)
Closed 4 years ago.
Got a basic if statement question, so I have an if statement in Java as shown here:
if (
!isOmitted(word,map.get(word.length()+1)) &&
!isInserted(word,map.get(word.length()-1)) &&
!isTransposed(word,map.get(word.length())) &&
!isSubstituted(word,map.get(word.length())) &&
!isCapital(word,map.get(word.length())))
{
noSuggestion=true;
}
where each individual method works perfectly as desired. Is there any way for java to check all conditions even when one is false? I know that the nature of the && operator is that as soon as a condition does not hold true, there is no point in checking the remaining conditions, as the entire condition is going to be set to false, but I was hoping I could do something like this in order to keep my code someone cleaner. I know I can use boolean variables, and assign the returned value to 5 different variables, but is there any other work around to force every condition to be checked? Thanks a lot in advanced
A single & is a non-short-circuit operand - ie both sides are evaluated irrespective of whether required.
More info here - https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.22.2
However, this sounds like a poor design. In fact, some code analysis tools would automatically flag these operators as suspicious for this reason. Typically you would want to call each method as they make some change to the state of your objects, which is not something you would expect in an if statement. But your method names do not suggest this. What are you trying to achieve?
This question already has answers here:
Java do while loop making string testing act differently
(3 answers)
Closed 6 years ago.
First let me start off by saying I'm new to Java and I'm not a professional programmer but I have written several macros in VBA.
I'm trying to help my son with his high school Java assignment. In the assignment there is a point where the user has a Y or N input. I can't figure out why this code doesn't work.
// Wait for user to press Y or N
do{
playAgain = input.next();
} while (!playAgain.equalsIgnoreCase("n") || (!playAgain.equalsIgnoreCase("y"));
It works if I only check for one condition.
Your logic says to continue looping so long as the input does not equal n/N or y/Y. This will always be true for both yes and no inputs, and in fact all inputs. If no is entered, the first condition would fail, but the second would be true, and vice-versa for yes.
To remedy this, you should && together the two conditions:
do {
playAgain = input.next();
} while (!playAgain.equalsIgnoreCase("n") && (!playAgain.equalsIgnoreCase("y"));
|| means OR. So, A || B is true if A is true or B is true. Any Or condition works like this: If first part if true, then second condition is not evaluated. If first is false, then second is evaluated. If either is true, then the result is true.
In your do while loop: !playAgain.equalsIgnoreCase("n") will be true if "y" is equal to your input and vice versa. Either way any one of the condition will always be true in the while loop condition, so the loop will go forever. The solution is mentioned in the answer given above. (use && instead of ||)
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
So I'm trying to check a list of account names to see if the username entered by the operator is in the database or not. At the moment I have:
for(int i = 0; i < rowCount; i ++){
System.out.println("Stored in array:" + accounts[i+1]);
System.out.println("name entered:" + LoginPage.usrname);
if(accounts[i+1] == LoginPage.usrname){
System.out.println("match");
}else{
System.out.println("no match");
}
}
I tried messing around with things like indexOf string and can't get anything to work. I'm sure there's a simple solution, just having trouble finding one. I don't understand why I can't compare a String array index to a String variable, seems like ti should be cake.
This is what you're looking for:
if(acounts[i+1].equals(LoginPage.usrname))
Using the == operator on Strings in Java doesn't do what you think it does. It doesn't compare the contents of the Strings, but rather their addresses in memory. The equals method compares the contents of the Strings.
As a note that may help you remember, this isn't anything particularly special about Strings. Strings are objects, and in Java, using == to compare objects of ANY type will present the same problem. If you want to compare the contents of two objects of a custom class you create, you'll have to write an equals method for that class. Strings work exactly the same.
String are unique reference type that behave like value type.
At Java when trying to compare String's using == operator, Java will try to check if both of the reference are equals, Not the strings.
In order to achieve a value type comparison you will be to use one of the following:
Method 1: str1.equals(str)
Method 2: str1.compareTo(str) == 0
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
im new to android and this is my first post in StackOverflow.In short I face a very strange problem :
in some methods I used if(...) ,and both of the values were equal ,yet it doesn't go through the if .
Here is an example :
String []s=db.getStudentsNames();
String []t=CopyNames(s);
String t1,t2;
t2=Id.getText().toString();
for(int i=0;i<s.length;i++)
{
t1=t[i].substring(t[i].indexOf("-")+1).toString();
Notifications(t[i].substring(t[i].indexOf("-")+1).toString());
if(t1.toString()==t2.toString())//Problem!
{
Notifications("Id already exists for "+t[i].substring(0,t[i].indexOf("-")).toString());
return false;
}
}
The variables t1 & t2 are : t1="123456789" & t2="123456789" , yet it doesn't enter the if like they are not equal.
And there are other places were two equal sides are considered as not equal - in the same java page (activity) like:
if(add.getText().toString()=="Add Student") : add refers to a button which has ,by default , a text :"Add Student"
so how can I solve this problem ?
**when this problem started , I started to see in LogCat:
W/KeyCharacterMap(282): No keyboard for id 0
W/KeyCharacterMap(282): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
D/dalvikvm(282): GC_FOR_MALLOC freed 5438 objects / 256800 bytes in 73ms
You shouldn't use == to compare Strings in Java. Use t1.toString().equals(t2.toString()) instead.
never use == on String objects. Use t1.equals(t2) instead.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why boolean in Java takes only true or false? Why not 1 or 0 also?
I was wondering today why Java cannot test any other type than a boolean.
In C, C++ and many other languages (actually most programming languages), the following is possible and valid:
int a = 0;
if (a) // evaluates to false
; // do something nice
a = 6;
if (a) // evaluates to true
; // do something more
This also works almost everywhere for objects, arrays; anything that can have a value of 0x00000000 in the memory.
The question: why is this not possible in Java (you have to keep on testing for == 0 or == null)?
I would guess that the rationale why is because it simplifies things.
An if statement has to evaluate a value to one of two possible conditions. What Java does is require you to supply a statement itself that must evaluate to two possible conditions (boolean) rather than accept other values and arbitrarily decide if that evaluates to true or false.
Because James Gosling et al decided that Java wouldn't do that.