我正在研究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;
}
}
}
因为_userHappinessLevel的数据类型是int,当你把这个变量放在switch中时,case应该是数字,或者你可以使用enum来做一些事情,比如给字符串一个“int”这个名字。