注释部分所在的位置表示存在 StackOverflowError
- null
。我试图让它生成随机数以与输入的值匹配。此代码的目标是执行以下操作:
- 接受最高数字(即 1000,以获得 (1-1000) 的范围)。
- 接受输入作为计算机猜测的数字。
- 计算机随机猜测第一个数字并检查它是否正确。
- 如果不正确,它应该通过一个循环并随机猜测数字,将它们添加到 ArrayList 中,直到猜测输入。它应该检查猜测值是否已经在数组中,并生成另一个随机数,直到生成一个不在列表中的随机数。
- 最后,它将使用 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/