为什么我会收到“变量可能尚未初始化"的信息?我的开关块中出现编译器错误? [英] Why do I get a "variable might not have been initialized" compiler error in my switch block?
问题描述
使用开关块时遇到可能未初始化变量"错误.
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
是final
,编译器也不会假定month
变量保留其2
值.
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
块之前将其初始化.
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);
这篇关于为什么我会收到“变量可能尚未初始化"的信息?我的开关块中出现编译器错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!