Dan
Dan

Reputation: 55

Output to a single dialog box depending on user input

When I compile I get an error message saying 'message' hasn't been initialized. What I'm trying to accomplish is instead of having multiple JOptionPane.showMessageDialog statements, I just want one statement in my code that will output any of the messages listed below depending on the user input.

int dogs;
        String message;
        dogs = Integer.parseInt(JOptionPane.showInputDialog("How many dogs do you have?"));     
        if (dogs >= 6)
        {
          message = "That is totally unbelieveable.";
        }
        else
        {
          switch (dogs)
          {
            case 0: message = "You really should get a dog. They're great pets."; break;
            case 1: message = "Glad you have a dog."; break;
            case 2: message = "Two dogs are better than one."; break;
            case 3: message = "Three dogs is a lot."; break;
            case 4: message = "Four dogs is too many."; break;
            case 5: message = "Five dogs means you're a crazy person."; break;
            JOptionPane.showMessageDialog(null,message);
            default: JOptionPane.showMessageDialog(null,"Invalid input."); break;
          } // end switch
        } // end if

Upvotes: 0

Views: 2350

Answers (1)

Callum
Callum

Reputation: 879

Try initializing the string when declaring it.

String message = "";

OR

String message = null;

If dogs >= 6 it won't be outputted either. You need to move your message outside the if/else block.

if (dogs >= 6)
        {
          message = "That is totally unbelieveable.";
        }
        else
        {
          switch (dogs)
          {
            case 0: message = "You really should get a dog. They're great pets."; break;
            case 1: message = "Glad you have a dog."; break;
            case 2: message = "Two dogs are better than one."; break;
            case 3: message = "Three dogs is a lot."; break;
            case 4: message = "Four dogs is too many."; break;
            case 5: message = "Five dogs means you're a crazy person."; break;
            default: message = "Invalid input."; break;
          } // end switch
        } // end if

        JOptionPane.showMessageDialog(null,message);

Upvotes: 1

Related Questions