【发布时间】:2016-02-01 00:11:31
【问题描述】:
我写了一个程序,它会根据我输入的颜色输出一朵花。在 switch 语句中,我一直看到一个错误,指出“case 表达式必须是常量表达式”。我看不出我在哪里做错了。我还遇到了打印出花朵复数时态的问题(如果用户输入 2 或更高)。
代码如下:
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 + ".");
}
}
【问题讨论】:
-
不能在 case 语句中使用变量。它们必须是常量。
标签: java eclipse switch-statement