0

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() 方法中的所有其他响应。

4

2 回答 2

1

鉴于您的逻辑,您的getRandomResponse方法应始终返回“OMG”。这是因为在该方法中第一次运行循环时,counter = 1。因此第一个 if 语句将运行并将返回“OMG”退出该方法。一个更好的等价物可能会将所有响应放入一个数组并从中返回一个随机值,而不是在迭代中做一些奇怪的事情:

String[] responses = {"OMG", "LOL", "You don't say", "Really?", "I See"};
return responses[(int)(Math.random() * responses.length)];
于 2013-12-08T21:17:04.157 回答
0

In getRandomResponse, you make a random number generator using Random(), but you never use it. Then in your for loop, you execute your decision-making tree but use a variable counter that always begins at 0. Then on the first time through your loop, the first if statement will execute because 0 < 5, so "OMG" is returned.

Edit: I just noticed something else that is not going to work in your code:

Random randomNumber = new Random();
for (int counter =0; counter<10; counter++)
{
    counter = randomNumber.nextInt();

You're trying to use counter to do two different things: you are trying to run this loop 10 times, but you're also using it to store random values.

于 2013-12-08T21:22:01.057 回答