gpt4 book ai didi

java - switch语句eclipse错误: case expressions must be constant expressions

转载 作者:行者123 更新时间:2023-11-29 06:30:40 24 4
gpt4 key购买 nike

我写了一个程序,可以根据输入的颜色输出一朵花。在 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 + ".");
}

最佳答案

将变量redpurple等标记为final。

final String red = "red";
final String blue = "blue";
final String yellow = "yellow";

关于java - switch语句eclipse错误: case expressions must be constant expressions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35121169/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com