ChatBot中剩下的最后一部分。我需要想办法修改chatbot类 它偶尔会(比如30%的时间)返回一个随机生成的标准回复,用户输入至少五个可能的回复之一,如“LOL”,“OMG”,“你不说”,“真的?“或”我看到了。“
编辑:应用推荐的更改:
import java.util.Random;
import java.util.Scanner;
public class ChatBot
{
private int responseCount = 0;
public String getResponse(String value)
{
String X = longestWord(value);
this.responseCount++;
if (responseCount == 10)
{
return "Sorry, but our time is up. I can't talk with you any longer.";
}
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?";
}
else if (X.length() <=9)
{
return "Now we are getting somewhere. How does " + X + " affect you the most?";
}
return getRandomResponse();
}
public String longestWord(String value){
Scanner input = new Scanner (value);
String longest = new String();
longest = "";
while (input.hasNext())
{
String temp = input.next();
if(temp.length() > longest.length())
{
longest = temp;
}
}
return longest;
}
private String getRandomResponse()
{
String [] responses = {"OMG", "LOL", "You don't say", "Really?", "I See"};
return responses [(int)(Math.random() * responses.length)];
}
}
问题是,它不断返回相同的响应,而不是给出的五个响应中的一个。我非常感谢任何帮助,谢谢!
编辑:它现在只给出随机响应,并覆盖getResponse()方法中的所有其他响应。
答案 0 :(得分:1)
根据您的逻辑,您的getRandomResponse
方法应始终返回“OMG”。这是因为在该方法的第一次循环运行时,counter = 1.因此第一个if语句将运行并返回“OMG”退出该方法。一个更好的等价物可能会将所有teh响应放入一个数组并从中返回一个随机值,而不是通过迭代做一些奇怪的事情:
String[] responses = {"OMG", "LOL", "You don't say", "Really?", "I See"};
return responses[(int)(Math.random() * responses.length)];
答案 1 :(得分:0)
在getRandomResponse
中,您使用Random()
创建一个随机数生成器,但您从未使用它。然后在for
循环中执行决策树,但使用始终以counter
开头的变量0
。然后在第一次循环时,第一个if
语句将执行,因为0 < 5
,因此返回"OMG"
。
编辑:我刚刚注意到其他一些在你的代码中不起作用的东西:
Random randomNumber = new Random();
for (int counter =0; counter<10; counter++)
{
counter = randomNumber.nextInt();
您尝试使用counter
执行两项不同的操作:您尝试运行此循环10次,但您也使用它来存储随机值。