根据用户输入输出到单个对话框

时间:2013-09-20 16:49:35

标签: java joptionpane

当我编译时,我收到一条错误消息,说“消息”尚未初始化。我想要完成的是不是有多个JOptionPane.showMessageDialog语句,我只想在我的代码中输出一个语句,它将根据用户输入输出下面列出的任何消息。

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

1 个答案:

答案 0 :(得分:1)

尝试在声明字符串时初始化字符串。

String message = "";

OR

String message = null;

如果狗> = 6,它也不会被输出。您需要将消息移到if / else块之外。

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