Java 2D game random rectangles

100 views Asked by At

I'm trying to make a simple javagame. One of the methods creates a new rectangle with random x and y values, and then it adds them to a list. I want my program to check if the new rectangle that is going to be added, intersects with one of the current ones and if it does, it should get new x and y values.

I've made a method that should work, but somehow it doesn't, I get the error:

Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException.

The code for the method is:

  public void addObstacle() {
    int x = (int)((Math.random() * 10)) * 40;
    int y = (int)((Math.random() * 10)) * 20;
    Rectangle newRec = new Rectangle(x, y, 20, 20);

    for(Rectangle r : obstacles) {

        if(newRec.intersects(r)) {
            System.out.println("The new rectangle does intersect with " + r);
        }
        else {
            obstacles.add(newRec);
        }
    }

    repaint();
}

Thanks in advance.

Update: Fixed by adding:

 Boolean doesCollide = false;
    for(Rectangle r : obstacles){

        if(newRec.intersects(r)){
            System.out.println("The new rectangle does intersect with " + r);
            doesCollide = true;
        }

    }

    if(!doesCollide){
        obstacles.add(newRec);
    }
1

There are 1 answers

2
Amit.rk3 On

This happens when you try to modify a collection while you are looping over it. here you are doing obstacles.add(newRec); while looping over obstacles . You can use ListIterator to modify collection. That way you won't get this exception