如何在两个值之间创建一个随机数?

时间:2013-12-30 01:54:01

标签: java artificial-intelligence computer-science

我有一个应用程序,它应该猜测/找出用户输入的数字,然后根据用户对其猜测的响应更改其猜测。我目前的代码就是这个。

public void askUsersNextChoice()
{
    if(itsGuess != itsSecretNumber)
        itsGuess = randy.nextInt(((itsLargeNumber - itsSmallNumber)) + 1) + itsSmallNumber;

    boolean myBool = true;

    while(myBool)
    {
        String s = JOptionPane.showInputDialog("                   My guess is: " + itsGuess + "\n\n1.) Too High?\n2.) Too Low?\n3.) Exactly Right?\n\n              Number of Guesses: " + itsTries + "\n ");
        if(s != null)
        {
            s = s.toLowerCase();
            switch(s)
            {
                case "too high":
                {
                    if(((itsLargeNumber - itsSmallNumber) + 1) < 101 && ((itsLargeNumber - itsSmallNumber) + 1) > 0)
                        itsLargeNumber = itsLargeNumber - (itsLargeNumber - itsGuess);

                    if(itsGuess == itsSecretNumber){
                        JOptionPane.showMessageDialog(null, "Don't you lie to me now...");
                        break;
                    }

                    myBool = false;
                    itsTries++;
                    break;
                }
                case "too low":
                {
                    if(((itsLargeNumber - itsSmallNumber) + 1) < 101 && ((itsLargeNumber - itsSmallNumber) + 1) > 0)
                        itsSmallNumber += itsGuess;

                    if(itsGuess == itsSecretNumber){
                        JOptionPane.showMessageDialog(null, "Don't you lie to me now...");
                        break;
                    }

                    myBool = false;
                    itsTries++;
                    break;
                }
                case "exactly right":
                {
                    myBool = false;
                    break;
                }
                default:
                {
                    JOptionPane.showMessageDialog(null, "Invalid Input!");
                    break;
                }
            }
        }
        else
        {
            System.exit(0);
            break;
        }
    }
}

问题在于,经过这么长时间,它将抛出异常:

  

java.lang.IllegalArgumentException:n必须为正

根据用户是否表示其先前的猜测“太高”或“太低”,它会在产生新猜测的行处抛出它。我一直试图解决这个问题几个小时而没有运气。如果有人知道如何正常工作,我将不胜感激。 :)

0 个答案:

没有答案