JOptionPane一旦单击取消按钮,如何退出代码

时间:2018-07-28 01:41:02

标签: java

我正在尝试创建一个聊天机器人,该机器人将继续询问有关输入主题的问题,直到用户单击“取消”按钮为止。对编码不熟悉,我不确定如何检查是否单击了取消按钮,但据我所知,一旦单击了按钮,它将返回“ null”。我认为下面的代码很接近,但是每当我取消时都会产生一条错误消息。

代码:

JOptionPane.showMessageDialog(null, "Hi! This is your chatbot. We will now begin the input taking phase");

        String topicOne = JOptionPane.showInputDialog("Please enter topic 1");
        String topicTwo = JOptionPane.showInputDialog("Please enter topic 2");
        String topicThree = JOptionPane.showInputDialog("Please enter topic 3");


        JOptionPane.showMessageDialog(null, "Thank you for the topics, we will now begin the chatting phase");

        String response = "hello";
        boolean questionMark;
        boolean containsTopicOne;
        boolean containsTopicTwo;
        boolean containsTopicThree;

        while (response != null) {
            response = JOptionPane.showInputDialog("Please tell me more about " + topicOne + ", " + topicTwo + ", " + topicThree + "...");
            questionMark = response.indexOf('?') >= 0;
            containsTopicOne = response.indexOf(topicOne) >= 0;
            containsTopicTwo = response.indexOf(topicTwo) >= 0;
            containsTopicThree = response.indexOf(topicThree) >= 0;

            if (questionMark == true) {
                JOptionPane.showMessageDialog(null, "I'll be the one asking the questions!");
                questionMark = false;
                containsTopicOne = false;
                containsTopicTwo = false;
                containsTopicThree = false;
            }
            else if (containsTopicOne == true || containsTopicTwo == true || containsTopicThree == true){
                JOptionPane.showMessageDialog(null, "NIce to know!");
                questionMark = false;
                containsTopicOne = false;
                containsTopicTwo = false;
                containsTopicThree = false;
            }
            else {
                JOptionPane.showMessageDialog(null, "Stay on topic!");
                questionMark = false;
                containsTopicOne = false;
                containsTopicTwo = false;
                containsTopicThree = false;
            }
        }
}

错误消息: 线程“主”中的异常java.lang.NullPointerException     在actionPerformed.main(actionPerformed.java:31)

对于简化代码,任何帮助或建议都将非常感谢。

1 个答案:

答案 0 :(得分:0)

这是一个示例是/否:

if (JOptionPane.showConfirmDialog(null, "Are you sure?", "WARNING",
        JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
    // yes selected
} else {
    // no selected
}