为什么我得到一个“变量可能没有被初始化"?我的开关块中的编译器错误?
我在使用 switch 块时遇到变量可能尚未初始化"错误.
I'm encountering "a variable might not have been initialized" error when using 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 块中为其分配值时我没有初始化它吗?
To my knowledge this error occurs when you try access a variable you have not initialized, but am I not initializing it when I assign it the value in the switch block?
同样,即使月份是编译时常量,我仍然会收到相同的错误:
Similarly, even if the month is a compile-time constant, I still receive the same error:
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
.
If month
isn't 1
or 2
then there is no statement in the execution path that initializes monthString
before it's referenced. The compiler won't assume that the month
variable retains its 2
value, even if month
is final
.
JLS,第 16 章, 讨论明确赋值"以及变量在被引用之前可能被明确赋值"的条件.
The JLS, Chapter 16, talks about "definite assignment" and the conditions under which a variable may be "definitely assigned" before it's referenced.
条件布尔运算符 &&、|| 和 ? 的特殊处理除外: 对于布尔值常量表达式,流分析中不考虑表达式的值.
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
在被引用之前没有明确赋值.
The variable monthString
is not definitely assigned prior to being referenced.
在 switch
块之前初始化它.
Initialize it before the switch
block.
String monthString = "unrecognized month";
或者在 switch
语句中以 default
的情况对其进行初始化.
Or initialize it in a default
case in the switch
statement.
default:
monthString = "unrecognized month";
或者抛出异常
default:
throw new RuntimeExpception("unrecognized month " + month);
相关文章