Fur*_*ndo 18 java final case switch-statement
final int a = 1;
final int b;
b = 2;
final int x = 0;
switch (x) {
case a:break; // ok
case b:break; // compiler error: Constant expression required
}
/* COMPILER RESULT:
constant expression required
case b:break;
^
1 error
*/
Run Code Online (Sandbox Code Playgroud)
为什么我会遇到这种错误?如果我愿意final int b = 2,一切正常.
Rah*_*ate 15
switch语句中的case应该是编译时的常量.命令
final int b=2
Run Code Online (Sandbox Code Playgroud)
在编译时分配2to 的值b.但是以下命令在运行时分配2to 的值.b
final int b;
b = 2;
Run Code Online (Sandbox Code Playgroud)
因此,编译器抱怨,当它在switch语句的一个案例中找不到常量时.
Boz*_*zho 10
b可能尚未初始化,可以分配多个值.在您的示例中,它显然已初始化,但可能编译器无法知道(并且它不能).想像:
final int b;
if (something) {
b = 1;
} else {
b = 2;
}
Run Code Online (Sandbox Code Playgroud)
编译器需要一个常量switch,但值b取决于某些外部变量.
| 归档时间: |
|
| 查看次数: |
15091 次 |
| 最近记录: |