-3

I have a class called "Box" from which I would like to create a new object "cookiebox" with a random number of cookies between 20 and 30. However, the creation of the random number throws a StackOverflowError, according to my IDE apparently something to do with the seeding within "Random".

import java.util.Random;
public class Box {

    private int numberofCookies

    public Box (int numberofCookies) {
        this.numberofCookies=numberofCookies;
    }
    Random rand = new Random();
    Box cookiebox = new Box(rand.nextInt(11) + 20); 

Could somebody explain why the error gets thrown?

Mark Rotteveel
  • 90,369
  • 161
  • 124
  • 175
  • 3
    What do you think `Box cookiebox = new Box(rand.nextInt(11) + 20);` does? Every time you create a `Box`, that box will have a field `cookiebox`, so it needs to create a new `Box`, which will have a field `cookiebox`, so it needs to create a new `Box`, and so on and so on. – Mark Rotteveel May 08 '22 at 11:50
  • 1
    As an aside, the use of `Random` is unrelated to your problem, and the warning about seeding is a separate problem. – Mark Rotteveel May 08 '22 at 11:53

0 Answers0