为什么在 if 语句中初始化字符串似乎与在 switch 语句中初始化字符串不同?
2022-09-01 16:39:51
我正在学习Java,我正在制作简单的程序,以根据一些书籍示例找到一个月的季节。这两个类演示了测试值的两种方法:if/else if 语句和 switch 语句。我感到困惑的是用来保存季节的字符串。当我声明它只是与if语句一起工作时。但是对于 switch 语句,这样做会产生“局部变量季节可能尚未初始化”错误。String season;
public class IfElse {
public static void main(String args[]) {
int month = 5;
String season;
// isn't initialized, works fine
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
season = "Fall";
// this is okay
System.out.println("May is a " + season + " month.");
}
}
对于上述代码,在声明的同时不初始化 season 工作正常,但是如果以相同的方式声明,则交换机的最后一个 season 变量会产生错误。println()
以下代码不起作用:
public class Switch {
public static void main(String args[]) {
int month = 5;
String season;
// HAS to be initialized, currently causes error
switch(month) {
case(12):
case(1):
case(2):
season = "Winter";
break;
case(3):
case(4):
case(5):
season = "Spring";
break;
case(6):
case(7):
case(8):
season = "Summer";
break;
case(9):
case(10):
case(11):
season = "Fall";
break;
default:
System.out.println("Invalid month");
break;
}
System.out.println("May is a " + season + " month");
} // produces an error if season isn't initialized to null or ""
}
这是什么原因造成的?是将 switch 语句括起来的大括号,还是 switch 语句本身有问题?在 if 语句中初始化字符串与在 switch 语句中初始化字符串有何不同?我似乎无法理解这一点。
抱歉,如果这是非常明显的,或者如果这似乎是一个愚蠢的问题。