0

当我编译时,我收到一条错误消息,说“消息”尚未初始化。我想要完成的不是多个 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
4

1 回答 1

1

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

String message = "";

或者

String message = null;

如果dogs >= 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);
于 2013-09-20T16:55:33.293 回答