我是 Java 新手,这是我的聊天机器人代码的一部分。当我从 showMenu()
运行 createQuestions()
时,它似乎不起作用。 createQuestion()
的作用是让用户创建问题并与自己聊天。
问题就在这里
欢迎!
选择您的选项:
1) 添加问题
2)聊天(需要先添加问题)
3)了解更多城镇
4)退出
你:1
正在创建问题...如果您想停止,请输入“end” 问题? (它不会在这里暂停,因为我需要读取用户输入的内容并将其存储为问题)
你:
您想要多少回复? :
//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: ""
最佳答案
如果 txtEnter.getText()
返回空白,您将得到:
java.lang.NumberFormatException: For input string: ""
因为空白不能转换为数字。
因此您应该检查以确保 txtEnter.getText()
不会返回空白。
关于java - 我的 Java 聊天机器人代码不起作用,我不知道为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45570194/