Search code examples
javarecursionstack-overflow

How to solve StackOverflowError


I have this nextInt method that is giving me a stackoverflow error:

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

And is called by this line of code:

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

I understand why it's giving the error but I don't know how to fix it. I have a similar method in a different program that doesn't give me the error:

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

Which is being called by this line of code:

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

Any helpful pointers would be great!


Solution

  • first you need to define the random object on that scope also or if you are defining random object else then declare it global

    you need to do like htis

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