如何解决 StackOverflowError

How to solve StackOverflowError

我有这个 nextInt 方法,它给我一个 Whosebug 错误:

public int nextInt(int a){
        int n = rand.nextInt(a);
        return n;
    }

并被这行代码调用:

int index = rnd.nextInt(Words.size());

我明白为什么会报错,但我不知道如何解决。我在另一个程序中有一个类似的方法,但没有给我错误:

public int nextInt(int l, int h){
    int n = rand.nextInt(h - l + 1) + l;
    return n;
}

这行代码正在调用:

System.out.println(rand.nextInt(10,20)); //prints random num between 10 and 20 inclusive

任何有用的指示都会很棒!

首先,您还需要在该范围内定义随机对象,或者如果您定义的是其他随机对象,则将其声明为全局对象

你需要像 htis 那样做

public int nextInt(int a){

 // create random object
  Random rand = new Random();

 // check next int value
  int n = rand.nextInt(a);
  return n;
}

根据我的说法,递归没有发生(事实上,这似乎是 方法重载 的情况)在下面的场景中:

public int nextInt(int l, int h){
    int n = rand.nextInt(h - l + 1) + l;
    return n;
}

因为 nextInt 方法有两个参数,而在 int n = rand.nextInt(h - l + 1) + l; 你只用一个参数调用 nextInt

而在第一种情况下,nextInt 方法只有一个参数,而在此方法中,您正在使用单个参数递归调用相同的 nextInt 方法。