Reputation: 1
i am making a shooting game as a project where the enemy object shoots randomly at the actor. but each time the enemy shoots at random, a java.util.ConcurrentModificationException is thrown. this is the code for shooting randomly
public void enemyAttackStrategy() {
// Fire at when at around the 1/4, 1/2 and 3/4 in a random direction
int width = Gui.getInstance().getWidth();
int firstPoint = width / 4 ;
int secondPoint = firstPoint * 2;
int thirdPoint = firstPoint * 3;
int dist = 2;
boolean nearFirst = (getX() - firstPoint) < 3 && (getX() - firstPoint > 0) ;
boolean nearSecond = (getX() - secondPoint) < 3 && (getX() - secondPoint > 0) ;
boolean nearThird = (getX() - thirdPoint) < 3 && (getX() - thirdPoint > 0);
if(nearFirst || nearSecond || nearThird){
//System.out.println("near!!!!!!!!" + (firstPoint) + " " + (secondPoint) + " " + (thirdPoint));
Game.getInstance().enemyShot();
}
and the code that creates the enemybullet
public void enemyShot() {
Bullet bullet = new Bullet("EnemyBullet", "Bullet.png", 14);
bullets.add(bullet);
int minSpeed = -15;
int xPosition = enemyShip.getX();
int yPosition = enemyShip.getY();
int xSpeed = random.nextInt(30) + minSpeed;
int ySpeed = random.nextInt(30) + minSpeed;
addToWorld(bullet, xPosition, yPosition, xSpeed, ySpeed, 2);
//System.out.println("Added Enemy Bullet");
}
this is the for loop its referring me to
public void timer() {
for (Tame oneTame : tames) {
tame.timeTick();//}
}
and this is the error
java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:886)
at java.util.ArrayList$Itr.next(ArrayList.java:836)
at GameFrameworkJavaFX.Game.timeTick(Game.java:135)
Upvotes: 0
Views: 170
Reputation: 700
A ConcurrentModificationException can happen if you have two threads going that are both modifying the same code. This is commonly caused if you have a for each loop modifying the contents of an array. See this question for further details about that specific problem. I don't know if that's what's causing the problem, but like @alfasin commented, we can't answer this question without seeing the code that is calling these methods.
Edit: Seeing your newly posted code, it looks like this very likely the case. Again, just check out this question, as this seems to be an error someone else had of exactly the same type.
Upvotes: 2