测试环境:jdk1.8
常量类:
public class MyConstant {
public static final int ONE=1;
public static final int TWO=2;
public static final int THREE=3;
}
调用类:
public class Test {
public static void main(String[] args) {
MyConstant constant=new MyConstant();
int number=2;
switch(number) {
case constant.ONE
:这里报
case expressions must be constant expressions
System.out.println(“1”);
break;
case constant.TWO:
System.out.println(“2”);
break;
case constant.THREE:
System.out.println(“3”);
break;
}
}
}
解决办法:不用new MyConstant类,直接用类名直接调用常量参数即可,如下
public class Test {
public static void main(String[] args) {
// MyConstant constant=new MyConstant();
int number=2;
switch(number) {
case MyConstant.ONE:
System.out.println(“1”);
break;
case MyConstant.TWO:
System.out.println(“2”);
break;
case MyConstant.THREE:
System.out.println(“3”);
break;
}
}
}