I'm having trouble with these if statements and can't figure out the problem:
If I try changing them to a nested if, else if format I get a compiler error saying "else" with no if statement.
The if statements don't even work, as you can see from the ouput below they all run even when the strings aren't equal.
Any help would be great. Thanks!
if (labelArray[0] == e.getSource() && myAppliance.size() >= 1) {
if (myAppliance.get(0).getClass().getName().toUpperCase().equals("CLOCK")); {
System.out.println(options[0]);
System.out.println(myAppliance.get(0).getClass().getName());
infoBox((myAppliance.get(0).toString()),"Info");
}
if (myAppliance.get(0).getClass().getName().toUpperCase().equals("LAMP")); //"Clock", "Lamp", "Television"
{
System.out.println(options[1]);
System.out.println(myAppliance.get(0).getClass().getName());
infoBox((myAppliance.get(0).toString()),"Info");
}
if (myAppliance.get(0).getClass().getName().toUpperCase().equals("TELEVISION")); {
System.out.println(options[2]);
System.out.println(myAppliance.get(0).getClass().getName());
infoBox((myAppliance.get(0).toString()),"Info");
}
}
Output:
Clock
Clock
Lamp
Clock
Television
Clock
Remove the ; at the end of the lines with the ifs.
remove the ; from immediate after if statements, compilers take them as statements and it defeats the purpose of using if itself.
Ifs work on the next statement they can take, so they'll run on the next line or treat a block enclosed on curly braces as a statement. By writing ; after the if, it's basically using an empty statement, then just proceeding to execute your block of code regardless.
Just remove the ; and it should work.
Related
In Java, if should have {} except when there is only one line under if.
But then, why can the following code run on my computer?
int x=1;
int y=1;
if(x<=4)
if(y>=4)
System.out.println("%%%");
else
System.out.println("+++");
System.out.println("***");
Here is what it looks like on my IDE:
And everything runs good. Here is the result (under it loading other resources, don't care about that. I just modified some of my code to try out the code as soon as possible.)
Java will associate the else to the last candidate if.
Your code (with braces) is equal to
if(x<=4) {
if(y>=4) {
System.out.println("%%%");
} else {
System.out.println("+++");
}
}
System.out.println("***");
A candidate if is matched when there is exactly 1 statement (ending with semicolon) or block between the if and the else.
Thanks for you all and the problem solved.
The point is, if execute the next one statement or block.
Java considers the following code as a whole statement.
`if(y>=4)
System.out.println("%%%");
else
System.out.println("+++");`
And it follows the first if.
The last print is not in the scope of consideration, it's just caused by bad indentation.
This is your code
if(x<=4)
if(y>=4)
System.out.println("%%%");
else
System.out.println("+++");
System.out.println("***");
this is what java thinks
if(Boolean) go to next line
if(Boolean) ok this is false, go to else f
I have the following lines in my code:
if (command.equals("sort") && args.length == 2) {
//run some program
}
Someone suggests that I should use two separate if statements because there's no need to evaluate any of the other if statements if the command does not equal to "sort", regardless of whether or not the args length is correct.
So according to that that, I need to rewrite my code to:
if (command.equals("sort")) {
if (args.length == 2) {
//run some program
}
}
I know they both do the job, but my question is which one is better and more efficient?
No, that's not true. They call it short circuit, if the first condition evaluates as false, the second one would not be evaluated at all.
Well, since && is a short-circuit operator. So both the if statements are effectively the same.
So, in first case, if your command.equals("sort"), returns false, the following condition will not be evaluated at all. So, in my opinion, just go with the first one. It's clearer.
As stated, short circuit will cause the program to exit the if statement the moment a condition fails, meaning any further conditions will not be evaluated, so there's no real difference in the way the two formats are evaluated.
I would like to note that code legibility is negatively affected when you have several if statements nested within each other, and that to me is the main reason not to nest. For example:
if( conditionA && conditionaB && !conditionC ){
// Do Something
}
is much cleaner than:
if( conditionA ){
if( conditionB ){
if( !conditionC ){
// Do Something
}
}
}
Imagine that with 20 nested if statements? Not a common occurrence, sure, but possible.
They are the same. For your first example, any modern runtime will ignore the second expression if the first expression is false.
short circuiting is better which is done by && if you are check null case for a value and then apply a function on that object, short circuit operator works well. It stops from condition 2 to be executed if condition 1 is false.
ex:
String s=null;
if(s!=null && s.length())
This doesnt throw exceptions and also in most cases you save one more if check.
If the conditions are in the same order, they are exactly the same in terms of efficient.
if (command.equals("sort") && args.length == 2)
Will drop out if command.squals("sort") returns false and args.length will never be checked. That's the short-circuit operation of the && operator.
What it comes down to is a matter of style and readability. IMO When you start chaining too many together in a single if statement it can get hard to read.
Actually, it is called [Lazy_evaluation]: http://en.wikipedia.org/wiki/Lazy_evaluation
That's not really the question but note that if you want the two if evaluated, you can use & :
if (methodA() & methodB()) {
//
}
instead of
boolean a = methodA();
boolean b = methodB();
if (a && b) {
//
}
yeah, their suggestions are completely right. What I suggest you is to write the first check as:
"sort".equals(command)
Maybe it does not make sense in this case but in future. Use the static type first so you never need a null check before
Basically I'm quite new to Java and just been given some code which reads:
if (n > 1)
l--;
m = l;
Although I'm wondering whether this would be equivalent to either one of these, and if so which and why?
#1
if (n > 1) {
l--;
m = l;
}
OR
#2
if (n > 1) {
l--;
}
m = l;
It's equivalent to the second one. The if statement executes the next statement if its expression evaluates to true. It doesn't matter to the compiler if the next statement is a single statement (as it is in your original code sample) or a block (as it is in your second revision).
It's the same as the second block of code.
When you don't see braces following a "grouping" statement (the if statement, in your example), it means that only the next line falls within the scope of that grouping statement.
Going beyond what the question asks, languages such as Java, C/C++, and C# use braces to declare blocks of code, whereas languages such as Python use whitespace. You can think of line of code is a block by itself. Blocks can be incrementally built by combining more blocks. This is done by grouping blocks; in Java, this is done through curly braces. When the if statement is evaluated (or a for loop, or a while loop, etc), the next outermost block falls under that statement.
the 2nd option.
If there's no { }, only the following statement is part of the If case
Obviously #2, because a if statement only takes the first expression after it into account. That is why it is always important to use brackets around your statements, both for clarity and fewer bugs. There is nothing more frustrating than spending hours wondering why code doesn't work because you forgot to add a bracket somewhere
I had an if statement checking some value, And encountered a weird bug(Not sure!). My code was incorrect syntactically and in result it produced a wrong result, however eclipse didn't raised any error while compiling. Why My below code worked?
if((this.trackPointList.get(point).getTurnOutId().equals(seg.getSegRef().getTurnOut())) && seg.getSegRef().getKind().equals("arc")); // <---- See here I have semicolon
{
... code to run ...
}
Above code check only first condition and ignores seg.getSegRef().getKind().equals("arc") but I guess this should raised an issue at compile time, Am I right? My logic worked once I debugged it by skimming line by line and found this semicolon. I will appreciate if someone could explain, if it is a valid syntax.
Enlighten Me, Please!
The ; makes Java think that the body of the if conditional is complete, even if there is no other code preceding it. In effect, the code in the if statement is executed, but no body exists because the ; is there.
The { ...code to run...} is just a code block that executes, and anything declared inside that block is not visible outside the block. It will always run here because it's not part of the if block.
edit: here's another stack overflow question about the { } blocks: What do curly braces in Java mean by themselves?
The code is syntactically correct. You can write ifs without braces, like:
if(condition) statement;
Having empty statements is also valid. For instance this code is valid:
int a = 0;;
;;;
So an empty if is valid as well, although it doesn't make much sense :)
if(condition);
An if statement followed by a semicolon is called an "empty if statement".
It rarely is of any use, but it's syntactically legal.
You can write something like this
if ( doSomethingThatReturnsABoolean() )
; // Empty statement
else
doSomeOtherThing()
but it would be better to write
if ( !doSomethingThatReturnsABoolean() )
doSomeOtherThing()
Regarding your observation that only the first condition gets checked:
If the first condition returns false the second condition will not get checked, because
(false && secondCondition)
always equals to false, so the value of secondCondition is irrelevant.
The ; after the if(..) statement represents an empty statement that is executed conditionally when the if(..) evaluates to true. The { .. } represents a code block that always executes with it's own scope.
The second condition may be ignored if the first condition is false due to short-circuit evaluation.
if(condition); is equivalent to if(condition){}
same thing with for loop & while loop:
for(;condition;); is equivalent to for(;condition;){}
while(condition); is equivalent to while(condition){}
I noticed that java (hence probably C) has no problem with this:
while(condition1) {
//do somethin'
} while(condition2);
Is this the same as:
while(condition1 && condition2) {
//do somethin'
}
No, you have two loops.
while(condition1) {
// do something
}
while(condition2); // second loop which does nothing.
The second loop is the same as
while(condition2) { }
EDIT: My suggestion is to use the automatic formatter in your IDE regularly. Otherwise you can create formatting which suggests the code does things it doesn't.
example 1
if (condition)
statement1;
statement2;
statement3;
In this example, it appears that the first two statements are part of the if condition, but only the first is.
example 2
http://www.google.com/
statement;
Doesn't look like legal Java, but it is, not for the reasons the formatting suggests ;)
No, they are different.
The first while(condition1) will run first.
Then comes while(condition2), which has nothing after it except a single ; which means it's just some empty statement.
Remember that in control blocks like if, for, while, if you don't use the {} braces, then only the first immediate statement after it will be considered part of it.
Example:
if (condition)
System.out.println("hello"); // prints only if condition is true.
System.out.println("no"); // not bound to the 'if'. Prints regardless.
while (condition)
; // do nothing!
System.out.println("something"); // not bound to the while
Edit The empty while loop is mentioned in the Java code conventions
7.6 while Statements
A while statement should have the following form:
while (condition) {
statements;
}
An empty while statement should have the following form:
while (condition);
There is no construct is java as shown in the first form. You have probably seen
do {
} while (cond)
EDIT : You are misreading the first form. There should have been a line break after the }. This confused me as well.