为什么会出现编译错误? Java 无法访问 bar
的两个声明。
import java.util.Random;
public class SwitchTest {
public static void main(String[] args) {
Random r = new Random();
int foo = r.nextInt(2);
switch(foo) {
case 0:
int bar = r.nextInt(10);
System.out.println(bar);
break;
case 1:
int bar = r.nextInt(10) + 10; // Doesn't compile!!
System.out.println(bar);
break;
}
}
}
最佳答案
它们都在相同的词法范围内,这与执行可达性不同。
在每个 case
内的代码上加上大括号,它就会起作用。
关于java - switch局部变量编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18667055/