Switch statement eclipse error: case expressions must be constant expressions(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";
这篇关于Switch语句eclipse错误:case表达式必须是常量表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Switch语句eclipse错误:case表达式必须是常量表达式


- 如何使用WebFilter实现授权头检查 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01