dimanche 8 mai 2022

Why does java throw a Stack Overflow - Error when creating a new object with a randomly generated number? [duplicate]

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?




Aucun commentaire:

Enregistrer un commentaire