switch case 后使用常量类报case expressions must be constant expressions解决办法

  • Post author:
  • Post category:其他


测试环境: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;

}

}

}



版权声明:本文为vzdong1原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。