在switch语句中需要“常量表达式”? [重复]

问题描述 投票:-2回答:1

这个问题在这里已有答案:

我正在研究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;
            }

    }
}
java switch-statement
1个回答
0
投票

因为_userHappinessLevel的数据类型是int,当你把这个变量放在switch中时,case应该是数字,或者你可以使用enum来做一些事情,比如给字符串一个“int”这个名字。

© www.soinside.com 2019 - 2024. All rights reserved.