随机整数上的堆栈溢出

xXM*_*kXx 0 java stack-overflow random recursion

注释部分所在的位置说有StackOverflowError- null。我试图使它成为随机数以匹配输入的值。此代码的目标是执行以下操作:

  1. 接受一个最高数字(即1000,以使比例为(1-1000))。
  2. 接受输入作为计算机可以猜测的数字。
  3. 计算机随机猜测第一个数字,并检查它是否正确。
  4. 如果不正确,则应遍历循环并随机猜测数字,然后将其添加到ArrayList中,直到猜测到输入为止。它应该检查一下猜测是否已经存在于数组中,并会生成另一个随机数,直到它变成不在列表中的那个为止。
  5. 最后,它将使用count变量打印出迭代次数

码:

import java.util.*;

public class ArrNumGuess
{
    public static Integer top, input, guess, count;
    public static ArrayList <Integer> nums;
    public static void main ()
     {
        System.out.println("Please enter the top number");
        top = (new Scanner(System.in)).nextInt();
        System.out.println("Please enter the number to guess (1 - " + top + ")");
        input = Integer.parseInt(((new Scanner(System.in)).nextLine()).trim());
        nums = new ArrayList<Integer>(); //use nums.contains(guess);
        guess = (new Random()).nextInt(top) + 1;
        nums.add(guess);
        System.out.println("My first guess is " + guess);
        count = 1;
        if(guess != input)
        {
            guesser();
        }
        System.out.println("It took me " + count + " tries to find " + guess + " and " + input);
    }

    public static void guesser()
    {
         boolean check = false;
         while(!check)
        {
            guess = (new Random()).nextInt(top) + 1; //Stack Overflow - null
            if(nums.contains(guess) && !(guess.equals(input)))
            {
                count--;
                guesser();
            }
           else if(guess.equals(input))
           {
                check = true;
                System.out.println("My guess was " + guess);
                // nums.add(guess);
                count++;
            }
           else
           {
               System.out.println("My guess was " + guess);
                nums.add(guess);
                count++;
           }
        }
     }
 }
Run Code Online (Sandbox Code Playgroud)

And*_*cus 5

guesser()方法中,您正在调用自身:

if(nums.contains(guess) && !(guess.equals(input)))
{
    count--;
    guesser();
}
Run Code Online (Sandbox Code Playgroud)

它很有可能永远不会结束。但是所有这些都在while循环中,所以为什么不消除重复并以迭代的方式进行呢?