Java if-if-else behavior

后端 未结 7 675
夕颜
夕颜 2020-12-11 21:18

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\'

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-11 21:18

    First and foremost, best advice is to always use braces!

    Naturally, every else statement is attached to the nearest if-statement and this is evident from this link and this is why your code behaves this way. The compiler cares nothing about indentation.. You can write your entire code on one line, it'd still work as long as its syntactically correct.

    Also, if you want the output you expected, nesting an if-statement inside another if-statement (with no else-statement) is a primitive practice; this can simply be done with the && operator like this:

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

    You'd have gotten your desired output. I hope this helps.. Merry coding!

提交回复
热议问题