Switch语句eclipse错误:case表达式必须是常量表达式
我写了一个程序,它会根据我输入的颜色输出一朵花.在 switch 语句中,我一直看到一个错误,指出case 表达式必须是常量表达式".我看不出我在哪里做错了.我还遇到了打印出花朵复数时态的问题(如果用户输入 2 或更高).
I wrote a program that would output a flower based off the color I will input. In the switch statement, I keep seeing an error stating that the "case expressions must be constant expressions." I don't see where I am doing it wrong. I'm also having an issue of printing out the plural tense of the flower (if the user would input 2 or higher).
代码如下:
Scanner input = new Scanner(System.in);
int quantity;
String color;
String flowerType = "";
char extra;
System.out.print("Please enter a color: ");
color = input.next();
System.out.print("Please enter the quantity: ");
quantity = input.nextInt();
String red = "red";
String blue = "blue";
String yellow = "yellow";
String purple = "purple";
String white = "white";
switch(color){
case red:
flowerType = "rose";
break;
case blue:
flowerType = "iris";
break;
case yellow:
flowerType = "daffodil";
break;
case purple:
flowerType = "sage";
break;
case white:
flowerType = "dogwood";
break;
default:
System.out.println("Invalid color.");
}
switch(quantity){
case 1:
break;
default:
extra = 's';
break;
}
System.out.println("You have " + quantity + flowerType + extra + ".");
}
}
推荐答案
将变量red
、purple
等标记为final.
Mark the variables red
, purple
, etc, as final.
final String red = "red";
final String blue = "blue";
final String yellow = "yellow";
相关文章