I wrote a simple if/else
in my code which worked fine. Later I added another level of if
under the first, and was baffled by its behavior. Here's very simple code to recreate the situation:
public static void main(String[] args) {
boolean a = true;
boolean b = false;
if (a)
if (b)
System.out.println("a=true, b=true");
else
System.out.println("a=false");
}
It returns "a=false
", even though a
is true!
It turns out the else
binds with the nearest if
, although I have not found it documented anywhere, and eclipse does not highlight the mismatched indentation levels as an error (although it does correct it when formatting the file).
A very, very strong argument for using braces!
Where is the binding order of else
/if
documented?
And as a challenge,
Is there a way to make the above code do what the indentation makes you expect without adding braces?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…