switch语句上的“需要常量表达式”吗?

时间:2019-04-20 05:09:28

标签: java switch-statement

我正在处理switch语句。 Java编译器告诉我,我的案例(x,y,z,a)需要一个常量表达式;这是哪里来的,为什么我的代码不能运行switch语句?

public class JavaPractice {
    public static void main ( String[] args ) {

        System.out.println("What's your happinessLevel? From 0 - 10");
        int _userHappinessLevel = IO.readInt();

        if ( _userHappinessLevel < 0 ) {
            x = _userHappinessLevel;
        } else if ( _userHappinessLevel <= 3) {
            y = _userHappinessLevel;
        } else if ( _userHappinessLevel > 3 && _userHappinessLevel <= 6 ) {
            z = _userHappinessLevel;
        } else if ( _userHappinessLevel > 6 && _userHappinessLevel <= 10) {
            a = _userHappinessLevel;
        } else {
            b = _userHappinessLevel;
        }


        switch (_userHappinessLevel) {

            case x:
                IO.reportBadInput();
                break;
            case y:
                System.out.println("Hope you feel better");
                break;
            case z:
                System.out.println("You're getting there");
                break;
            case a:
                System.out.println(":)");
                break;
            default:
                IO.reportBadInput();
                break;
            }

    }
}

1 个答案:

答案 0 :(得分:0)

因为_userHappinessLevel的数据类型为int,并且将此变量放在switch中时,大小写应该为数字,否则您可以使用enum进行诸如为字符串指定“ int”名称的事情。