我在使用 switch block 时遇到“变量可能尚未初始化”错误。
这是我的代码:
public static void foo(int month)
{
String monthString;
switch (month)
{
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
}
System.out.println(monthString);
}
错误:
Switch.java:17: error: variable monthString might not have been initialized
System.out.println (monthString);
据我所知,当您尝试访问未初始化的变量时会发生此错误,但是当我在 switch block 中为它赋值时我是否没有初始化它?
同样,即使月份是编译时常量,我仍然收到相同的错误:
public static void foo()
{
int month = 2;
String monthString;
switch (month)
{
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
}
System.out.println(monthString);
}
最佳答案
如果 month
不是 1
或 2
则执行路径中没有初始化 monthString
的语句> 在它被引用之前。编译器不会假定 month
变量保留其 2
值,即使 month
是 final
。
JLS, Chapter 16 ,讨论了“明确赋值”以及变量在被引用之前可以“明确赋值”的条件。
Except for the special treatment of the conditional boolean operators &&, ||, and ? : and of boolean-valued constant expressions, the values of expressions are not taken into account in the flow analysis.
变量 monthString
在被引用之前没有明确赋值。
在 switch
block 之前初始化它。
String monthString = "unrecognized month";
或者在 switch
语句中的 default
情况下初始化它。
default:
monthString = "unrecognized month";
或者抛出异常
default:
throw new RuntimeExpception("unrecognized month " + month);
关于java - 为什么我的 switch block 中出现 "variable might not have been initialized"编译器错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28820579/