本文介绍了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 + ".");
}

}

推荐答案

将变量redpurple等标记为final.

Mark the variables red, purple, etc, as final.

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

这篇关于switch语句eclipse报错:case表达式必须是常量表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 18:22