随机整数上的堆栈溢出

时间:2019-09-19 15:43:41

标签: java recursion random stack-overflow

在注释部分的位置,它表示存在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++;
           }
        }
     }
 }

3 个答案:

答案 0 :(得分:5)

ListItem方法中,您正在调用自身:

@override
String toString() => 'ListItem a=$a b=$b';

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

答案 1 :(得分:0)

您正在使它变得比原来更复杂,并且不必要地引入了递归。递归是堆栈溢出的根源,因为它变得太深,无法正确“猜测”。 那里也有很多草率的现象。这是一个清理的版本:

import java.util.*;

public class Guess {
    public static void main(String args[]) {
        System.out.println("Please enter the top number");
        Scanner scanner = new Scanner(System.in);
        int top = scanner.nextInt();
        System.out.println("Please enter the number to guess (1 - " + top + ")");
        int input = scanner.nextInt();
        if (input < 1 || input > top) {
            System.out.println("That's not in range. Aborting.");
            return;
        }

        ArrayList <Integer> nums = new ArrayList<>();

        Random rng = new Random(System.currentTimeMillis());
        while(true) {
          int guess = rng.nextInt(top) + 1;
          if (!nums.contains(guess)) {
            nums.add(guess);
            if (nums.size() == 1) {
                System.out.println("My first guess is " + guess);
            } else {
                System.out.println("My guess was " + guess);
            }
            if (guess == input) {
                System.out.println("It took me " + nums.size() + " tries to find " + guess);
                break;
            }
          }
        }
    }
}

答案 2 :(得分:0)

确定-一种有趣的guesser娱乐方式。枚举指定范围(1到“ top”)内的随机数字序列,并在列表中找到其索引实际上是“尝试”次数的guess并返回。

(顺便说一句-@Andronicus的答案是正确的。)

/** Pass in 'guess' to find and 'top' limit of numbers and return number of guesses. */
public static int guesser(int guess, int top) {
    List<Integer> myNums;
    Collections.shuffle((myNums = IntStream.rangeClosed(1, top).boxed().collect(Collectors.toList())), new Random(System.currentTimeMillis()));        
    return myNums.indexOf(guess);
}