关于分支语句if else 的疑问

来源:百度知道 编辑:UC知道 时间:2024/05/12 03:51:09
程序如下:
class IfElse {
public static void main(String args[]) {
int month = 4; // April
String season;
if(month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";
System.out.println("April is in the " + season + ".");
}
}
}
这段的结果是 April is in the Spring
为什么会是spring?
season = "Bogus Month";这句是什么意思?
程序为什么会把minth=April归到Spring?

month = 4啊!
程序在判断时满足分支
if(month == 3 || month == 4 || month == 5)
所以执行分支后的语句
season = "Spring";

至于
Bogus Month
是因为一年就12各月,如果month的值不是1—12的话,那说明输入的值是无效的
比如:在开始时第三行输入month = 13;的话
经过if else 判断后输出season = "Bogus Month";
是因为13不是一年中的月份,因而提示你输入的月份无效。

else if(month == 3 || month == 4 || month == 5)
season = "Spring"; //意思就当month=4的时候执行这条语句。
//别的语句条件都不合适
//让season="Spring" spring是字符串
//所以在后面结果是spring

season = "Bogus Month"; //是月份错误的意思,
//就是说假如你输入了13
//系统会提示你出错。