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

标签 java eclipse switch-statement

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

相关文章:

java - 在java xquery处理器中使用OSB功能bea

java - 单击按钮更改 fragment

java - Eclipse 插件项目不显示在应用程序模型中添加的窗口

java - Eclipse PDE,创建控件

javascript - Switch 语句比较用户输入 Javascript

ruby - 将日期转换为星期几

java - 我在 android 上通过 bitmapToMat 得到了 CvException

java - 在 UserCredentialsConnectionFactoryAdapter Spring 4 中设置 targetConnectionFactory 时出错

java - 在多个 fragment 中显示日期

c++ - 在 switch 语句中初始化变量 (int32)