首先错误代码:
public static void main(String[] args) {
int type = 2;
switch (type) {
case 0:
int i = 0;
System.out.println(type);
break;
case 1:
int i = type;
System.out.println(i);
break;
case 2:
int i = type;
System.out.println(i);
break;
case 3:
int i = type;
System.out.println(i);
break;
}
}
?解决方法:
??? 使用java中的大括号来限定case中声明的变量的作用域
public static void main(String[] args) {
int type = 2;
switch (type) {
case 0: {
int i = 0;
System.out.println(type);
break;
}
case 1: {
int i = type;
System.out.println(i);
break;
}
case 2: {
int i = type;
System.out.println(i);
break;
}
case 3: {
int i = type;
System.out.println(i);
break;
}
}
}