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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…