Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch statement eclipse error: case expressions must be constant expressions

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).

Here's the code:

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 + ".");
}

}

like image 269
Skippy Avatar asked Dec 08 '25 05:12

Skippy


2 Answers

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

final String red = "red";
final String blue = "blue";
final String yellow = "yellow";
like image 130
DominicEU Avatar answered Dec 09 '25 19:12

DominicEU


Use string literals for the color name instead of using variables.

switch(color) {
case "red":
     ...
case "blue":
     ...
... //other cases also with ""
}
like image 24
ronIDX Avatar answered Dec 09 '25 19:12

ronIDX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!