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 + ".");
}
}
Mark the variables red, purple, etc, as final.
final String red = "red";
final String blue = "blue";
final String yellow = "yellow";
Use string literals for the color name instead of using variables.
switch(color) {
case "red":
...
case "blue":
...
... //other cases also with ""
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With