【发布时间】:2019-05-30 15:48:46
【问题描述】:
我正在学习 Java,我正在根据一些书籍示例编写简单的程序来查找一个月所在的季节。这两个类演示了两种测试值的方法:if/else if 语句和 switch 语句。我感到困惑的是用于保持季节的字符串。当我将它声明为 String season; 时,它适用于 if 语句。但是使用 switch 语句,这样做会产生“局部变量 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.");
}
}
在声明的同时不初始化季节对于上面的代码可以正常工作,但是如果以相同的方式声明,则开关的最后一个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 语句中初始化字符串有何不同?我似乎无法理解这一点。
对不起,如果这是非常明显的问题,或者这似乎是一个愚蠢的问题。
【问题讨论】:
-
在不起作用的代码中,第13个月是哪个季节?
-
Meta discussion 关于这个问题。
-
仅供参考,案例值周围不需要括号。
case 12:等很好。 -
顺便说一句,使用这样的未初始化变量是个好主意,因为它可以清楚地表明您是否考虑了所有路径(但是,如果示例显示您可能没有正确考虑它)。 (反对使用
String season = ““;,这在经验不足的程序员的代码中经常出现)我认为即将推出的案例表达式将使这成为更好的体验。 -
明确一点(因为没有一个答案是):这与
ifvsswitch无关。您的两段代码根本不等效,但您可以编写具有if和switch的等效代码(表现出任一行为)。
标签: java string if-statement switch-statement