Why do I get a quot;variable might not have been initializedquot; compiler error in my switch block?(为什么我得到一个“变量可能没有被初始化?我的开关块中的编译器错误?)
问题描述
我在使用 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);
这篇关于为什么我得到一个“变量可能没有被初始化"?我的开关块中的编译器错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我得到一个“变量可能没有被初始化"?我的开关块中的编译器错误?
基础教程推荐
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 降序排序:Java Map 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01