java - 随机整数上的堆栈溢出

标签 java algorithm if-statement math while-loop

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

最佳答案

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

if(nums.contains(guess) && !(guess.equals(input)))
{
    count--;
    guesser();
}

很可能它永远不会结束。但所有这些都在 while 循环中,那么为什么不摆脱重复并以迭代方式执行此操作呢?

关于java - 随机整数上的堆栈溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58014659/

相关文章:

Java Swing 字母数字键盘

java - 从 build.gradle 文件中读取静态 Java 类

java - 使用AndroidSequenceEncoder时收到 "No frames output"

algorithm - 匈牙利 (Kuhn Munkres) 算法古怪

algorithm - 如何通过添加最小边数来增加图中最小切割的大小

arrays - 对具有相同属性的对象进行分组

python - 在 Python 中创建一个函数,该函数会被除以直到达到某个范围

javascript - 在 HTML 中的 JavaScript 中插入 HTML

java - JMonkeyEngine-几何交集 NullPointerException

java - ';'预计在 if 之后