Java if-if-else behavior

后端 未结 7 688
夕颜
夕颜 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:22

    It is documented in Section 14.5 of the Java Language Spec:

    The problem is that both the outer if statement and the inner if statement might conceivably own the else clause. In this example, one might surmise that the programmer intended the else clause to belong to the outer if statement.

    The Java programming language, like C and C++ and many programming languages before them, arbitrarily decrees that an else clause belongs to the innermost if to which it might possibly belong. This rule is captured by the following grammar:

提交回复
热议问题