dimanche 10 octobre 2021

random.nextInt() gives out of bounds error

I have been trying to create an ArrayList that stores random shapes (objects overriding an abstract class) that I have created, in order to draw them later.

ArrayList<Shape> shapes = new ArrayList<Shape>();

 for (int i = 0; i < 20; i++) {
        int randomType = random.nextInt(4);
        //int randomType = 1;
        if (randomType == 1) {
            shapes.add(new Circle(800, 450)); 
        } else if (randomType == 2) {
            shapes.add(new Tree(800, 450));
        } else if (randomType == 3) {
            shapes.add(new Square(800, 450));
        }
    }

Every time I run the program I get a different index in the error, for example

Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index 16 out of bounds for length 16
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index 12 out of bounds for length 12
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index 8 out of bounds for length 8

If I initialize the randomType variable with just one value, it works well, but I need to have more shapes in the final drawing. I am quite new to Java, so I don't really understand what the problem with this code could be.

Any help would be greatly appreciated! Thanks!




Aucun commentaire:

Enregistrer un commentaire