I have this little game that I am developing in which the character goes through buttons that will remove barriers so that it can access other areas of the maze.
I created two lists, one for the fences and one for the buttons.
listaCercas = new ArrayList<Arbusto>();
listaCercas.add(new Arbusto(this,105, 496));
listaCercas.add(new Arbusto(this,660, 210));
listaBotoes = new ArrayList<Itens>();
listaBotoes.add(new Itens(this, 625, 460));
listaBotoes.add(new Itens(this, 200, 40));
And I put the following code in the part of the collisions:
Iterator<Itens> itbotao = listaBotoes.listIterator();
Iterator<Arbusto> it6 = listaCercas.listIterator();
while(it6.hasNext() && itbotao.hasNext()) {
Arbusto cerca = it6.next();
Itens botao = itbotao.next();
Rectangle rBotao = new Rectangle(botao.x, botao.y, botao.botaoL, botao.botaoA);
Rectangle rCerca = new Rectangle(cerca.x, cerca.y, cerca.cercaL, cerca.cercaA);
if(rBoneca.intersects(rCerca)) {
switch(direcao) {
case 1:
bonecaSprite.y -= 5;
break;
case 2:
bonecaSprite.x -= 5;
break;
case 3:
bonecaSprite.x += 5;
break;
case 0:
bonecaSprite.y += 5;
break;
}
}
if((rBoneca.intersects(rBotao) && rBotao.getX() == 625) && !On_Off) {
On_Off = true;
listaCercas.remove(1);
} else if((rBoneca.intersects(rBotao) && rBotao.getX() == 625) && On_Off) {
On_Off = false;
listaCercas.add(new Arbusto(this,660, 210));
}
if((rBoneca.intersects(rBotao) && rBotao.getX() == 200) && !On_Off) {
On_Off = true;
listaCercas.remove(0);
} else if ((rBoneca.intersects(rBotao) && rBotao.getX() == 200) && On_Off) {
On_Off = false;
listaCercas.add(new Arbusto(this,105, 496));
}
My code works if I have only one button, but when I put the other button and its code, Java throws me the error: java.util.ConcurrentModificationException
.
I've been searching the net and trying to better understand the problem and saw that it was about the iteration part but I do not know how to solve it. How to create more buttons on the following levels and not have to define each button with a variable?