Java behavior if-if-else

I wrote a simple one if/elsein my code that worked great. Later I added another level ifto the first one, and was confused by his behavior. Here is a 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", although atrue!

It turns out that it elsecontacts the nearest one if, although I did not find it documented anywhere, and eclipse does not highlight inconsistent levels of indentation as an error (although it fixes it when formatting the file).

A very, very strong argument for using braces!

Where is the binding order registered else/ if?

And as a challenge

Is there a way to make the above code what indentation you expect without adding curly braces?

+4
7

, ?

. Java Python, , . .

, else if, , , . JLS & sect; 14.5 -

+18

, ?

if (a)
    if (b)
        System.out.println("a=true, b=true");
    else;
else
    System.out.println("a=false");

else; , .

, - , , , . .

+11

14.5. :

Java "" ,

, : , if, else ( "short if statement" ), , .

, if, if, else.

+10

14.5 Java:

, if, if , , else. , else if.

Java, C ++, , , else , . :

+4

, ?

:

public static void main(String[] args) {
    boolean a = true;
    boolean b = false;

    if (!a)
        System.out.println("a=false");   
    else if(b)
        System.out.println("a=true, b=true");

}
+4
public static void main(String[] args) {
    boolean a = true;
    boolean b = false;

    if (a && b)
        System.out.println("a=true, b=true");
    else if (!a)
        System.out.println("a=false");
}
+1

, - !

, if-statement, . . , , .

Also, if you want the expected result, nesting an if-statement inside another if-statement (without an else-statement) is a primitive practice; this can simply be done using the operator &&as follows:

if (a && b)
        System.out.println("a=true, b=true");
else
    System.out.println("a=false");

You would get the desired result. Hope this helps ... Fun coding!

0
source

Source: https://habr.com/ru/post/1536995/


All Articles