我正在开发一个Chat Bot项目,而且我差不多完成了,除了每当我输入一个输入时,它会根据输入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!
答案 0 :(得分:0)
关于计算回复,只需修改主要方法:
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方法中?它根本没用过。仔细看看你的方法,因为他们拿着一些奇怪的代码。
答案 1 :(得分:0)
您正在使用Scanner.next方法,该方法仅返回字符串中的下一个单词。因此,如果您输入包含多个单词的字符串,您的机器人将对每个单词进行响应。
您可以使用Scanner.nextLine()来获取整个输入字符串,而不只是1个字。
要计算机器人响应的次数,您可以在机器人类中创建一个字段:
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"))
{
...