有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何解决StackOverflower错误

我有一个nextInt方法,它给了我一个stackoverflow错误:

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

任何有用的指针都会很好


共 (2) 个答案

  1. # 1 楼答案

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

    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方法进行递归调用

  2. # 2 楼答案

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

    你需要像htis那样做

    public int nextInt(int a){
    
     // create random object
      Random rand = new Random();
    
     // check next int value
      int n = rand.nextInt(a);
      return n;
    }