我正在做一个聊天机器人项目,我几乎完成了,除了当我输入一个输入时,它会根据输入X的长度返回多个输出。
以下是源代码:
import java.util.*;
public class ChatBot
{
public static String getResponse(String value)
{
Scanner input = new Scanner (System.in);
String X = longestWord(value);
if (value.contains("you"))
{
return "I'm not important. Let's talk about you instead.";
}
else if (X.length() <= 3)
{
return "Maybe we should move on. Is there anything else you would like to talk about?";
}
else if (X.length() == 4)
{
return "Tell me more about " + X;
}
else if (X.length() == 5)
{
return "Why do you think " + X + " is important?";
}
return "Now we are getting somewhere. How does " + X + " affect you the most?";
}
private static String longestWord(String value){
Scanner input = new Scanner (value);
String longest = new String();
"".equals(longest);
while (input.hasNext())
{
String temp = input.next();
if(temp.length() > longest.length())
{
longest = temp;
}
}
return longest;
}}
这是用于测试聊天机器人:
import java.util.Scanner;
public class Test {
public static void main (String [ ] args)
{
Scanner input = new Scanner (System.in);
ChatBot e = new ChatBot();
String prompt = "What would you like to talk about?";
System.out.println(prompt);
String userInput;
userInput = input.next();
while (!userInput.equals("Goodbye"))
{
System.out.println(e.getResponse(userInput));
userInput = input.next();
}
}
}
I am also trying to modify the Bot so it counts the number of times it has responded; and also modify it so it randomly returns a random response depending on the length of the input. Any help will be much appreciated. Thank You!发布于 2013-12-07 14:57:29
您使用的是Scanner.next方法,它只返回字符串中的下一个单词。因此,如果您输入一个字符串的多个字,您的机器人将响应其中的每一个。
您可以使用Scanner.nextLine()获取整个输入字符串,而不仅仅是一个单词。
要计算bot响应的次数,可以在bot类中创建一个字段:
private int responseCount = 0;然后,如果将yout getResponse方法从静态方法更改为实例方法,则可以从此方法更新此值:
public String getResponse(String value)
{
String X = longestWord(value); //Your longestWord should also not be static.
this.responseCount++;
if (value.contains("you"))
{
...发布于 2013-12-07 14:51:21
关于计算响应,只需修改您的主要方法:
import java.util.Scanner;
public class Test {
public static void main (String [ ] args)
{
int numberOfResponses = 1;
Scanner input = new Scanner (System.in);
ChatBot e = new ChatBot();
String prompt = "What would you like to talk about?";
System.out.println(prompt);
String userInput;
userInput = input.next();
while (!userInput.equals("Goodbye"))
{
System.out.println(e.getResponse(userInput));
userInput = input.nextLine();
numberOfResponses++;
}
input.close();
System.out.println(numberOfResponses);
}
}如果我有时间,我将在几分钟内编辑我的帖子,以检查你的问题有关的双重外观的回应。你还忘了关闭扫描仪。
编辑:实际上之所以发生这种情况,是因为扫描仪默认设置分隔符为空格。因此,如果使用空格输入文本,则会为一个用户输入运行两次while循环。只需使用nextLine()命令即可。
为什么这个代码:
Scanner input = new Scanner (System.in);在你的getResponse方法中?根本没用过。仔细看看你的方法,因为它们包含一些奇怪的代码。
https://stackoverflow.com/questions/20442547
复制相似问题