Skippy
Skippy

Reputation: 43

Switch statement assistance?

I am writing a problem that prompts the user to enter a color (red, blue, yellow, purple & white) & quantity, which will output a flower in the following output: You have [quantity] [type of flower]. Each color has to have at least two flowers assigned to them. As the title states, I have to have a switch statement in the program for the variable that initializes the type of flowers assigned to that color. Here is the sample of the switch statement I've written:

int quantity;
String color;
String flower;//the type of flower associate with the color

System.out.print("Please enter a color: ");
    color = input.next();
    System.out.print("Please enter the quantity: ");
    quantity = input.nextInt();

    switch(color){
    case red:
        System.out.println("You have one rose.");
        break;
    case blue:
        System.out.println("You have 2 blue irises.");
        break;

What am I doing wrong? I feel as if I have to include a possible if-statement as well.

Upvotes: 0

Views: 107

Answers (1)

Jake H.
Jake H.

Reputation: 969

You look to be on the right track. In your case statements, use the flower variable you defined above. Assign your type of flower for that color. Also, the actual case is a string, so it needs to be in double quotes.

switch (color) {
    case "red":
        flower = "rose(s)";
        break;
    case "blue":
        flower = "hydrangea(s)";
        break;
}

You can then call your println method after your switch statement like this:

System.out.println("You have " + quantity + " of " + flower);

Upvotes: 1

Related Questions