我的Java Chatbot代码不工作,我不知道为什么

问题描述:

我是Java新手,这是我的聊天机器人代码的一部分。当我从showMenu()运行createQuestions()它似乎不工作。 createQuestion()所做的就是让用户创建问题并与自己聊天。我的Java Chatbot代码不工作,我不知道为什么

问题就在这里

欢迎光临!

选择你的选项:

1)添加问题

2)聊天(您需要添加问题第一)

3)了解更多关于城镇

4)退出

您:1

创建问题...输入'en d'如果你想停止 问题? (因为我需要读什么用户输入并存储为问题并不在这里暂停)

您:

多少回应你想要什么? :

 //Start of ShowMenu(): 
     txtChat.append("\nWelcome!\nChoose your option:"); 
     txtChat.append("\n1)Add Questions\n2)Chat(You need to add question first)\n3)Know more about Towns\n4)Exit\n"); 
     txtChat.append(">>>\n"); 

     txtEnter.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       showMenu(); 
      }//end actionPerformed 

     });//end actionListener 

    }//end TestinChatBot 

    public void showMenu() { 
     String choice; 

     do { 

      switch (choice) { 
       case "1": 
        createQuestions(); 
        break; 
       case "2": 
        startChat(); 
        break; 
       case "3": 
        knowtowns(); 
        break; 
       case "4": 
        txtChat.append("\nFinally! I can play MapleStory! Sayonara!"); 
        System.exit(0); 
        break; 
       default: 
        break; 
      } 

     } while (!choice.equals("4")); 

    } 

    public void createQuestions() { 
     txtChat.append("\nCreating questions...Type 'end' if you wish to stop\n"); 

     do { 

      txtChat.append("Question? \n"); 
      q = txtEnter.getText(); 
      txtChat.append("You: " + q + "\n"); 

      if (!q.contains("end")) { 
       txtChat.append("How many responses do you want? : "); 
       noOfResponses = Integer.parseInt(txtEnter.getText()); 
       txtEnter.setText(""); 
       String r[] = new String[noOfResponses]; 
       if (noOfResponses > 0) { 
        for (int i = 0; i < noOfResponses; i++) { 
         txtChat.append("Response " + (i + 1) + ": "); 
         r[i] = txtEnter.getText(); 
         txtEnter.setText(""); 

        } 
        Chat newChat = new Chat(q, r); 
        addQuestion(newChat); 
        txtChat.append("\n" + Arrays.toString(r)); 
       } else { 
        txtChat.append("Please enter a number bigger than 0"); 

       } 
      } else { 
       showMenu(); 
      } 
     } while (q.equalsIgnoreCase("end") == false); 
    } 

,并且错误是这些

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "" 
+0

'choice'在哪里被分配? –

如果txtEnter.getText()回报空白您可以:

java.lang.NumberFormatException: For input string: "" 

因为空白无法转换为数字。

所以你应该检查以确保txtEnter.getText()不返回空白。

+0

我知道,但我的程序不会停止供用户输入,所以如何阻止它并让用户输入? – Ocean