Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
589 views
in Technique[技术] by (71.8m points)

java - Inconsistency with else statements?

This is a revised version of my previous question.

When using else-if as a shortcut, I'm not exactly sure why, syntax wise, it performs the same functionality as nesting if-else statements. Let's say you have the following:

int score = 80;
if(score < 80) {
  System.out.println("C Grade");
} else if(score < 90) {
  System.out.println("B Grade");
} else if(score < 100) {
  System.out.println("A Grade");
}

If I add some indentation, I get something similar to:

if(score < 80) {
  System.out.println("C Grade");
} else 
  if(score < 90) {
    System.out.println("B Grade");
  } else 
    if(score < 100) {
      System.out.println("A Grade");
    }

This evaluates the same as writing nested if-else statements as such:

if(score < 80) {
    System.out.println("C Grade");
} else { 
    if(score < 90) {
        System.out.println("B Grade");
    } else { 
        if(score < 100) {
        System.out.println("A Grade");
        }
    }
}

I see a major difference, however. In the third code snippet, the "else" statement has brackets, and the remaining if-else statements are nested inside those brackets. While in the first scenario, there are no encapsulating brackets. So why does the first idea of else-if work, if I seemingly need to have brackets when nesting if-else statements? I thought that a lack of brackets with control flow statements such as if, else, while, etc. cause the compiler to only evaluate the following line, such as:

if(condition)
    System.out.println("A");
    System.out.println("B");
//only prints "A"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If there are no brackets, the following statement is used, not just the following line.

An if-statement consists of

if (<condition>) <statement> else <statement>

It does not matter if it's written on several lines. In general, line breaks can occur in Java everywhere where white space is allowed without changing the meaning (the only exceptions are within string literals and one line comments).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...