So I have 2 arraylists (player1List, and player2List) each of which have 26 ints in them. I run them through a for-loop comparing two numbers from each. If one list has a number that is bigger than the other, the smaller number gets added to the winning list. However, when I run it through the for-loop at a certain point I get an "indexOutOfBoundsException: Index 21: Size 21." How do I get to run through the loop until one of the arraylists is empty? Here is my code.
for (int i = 0; i < player1List.size; i++){
if (player1List.get(i) < player2List.get(i)){
System.out.printf("Player 1: %d\n", player1List.get(i));
System.out.printf("Player 2: %d\n", player2List.get(i));
System.out.printf("Player 2 wins round!\n");
player2List.add(player1List.get(i));
player1List.remove(player1List.get(i));
}
if (player1List.get(i) > player2List.get(i)){
System.out.printf("Player 1: %d\n", player1List.get(i));
System.out.printf("Player 2: %d\n", player2List.get(i));
System.out.printf("Player 1 wins round!\n");
player1List.add(player2List.get(i));
player2List.remove(player2List.get(i));
}
if (player1List.get(i) == player2List.get(i)){
System.out.printf("Player 1: %d\n", player1List.get(i));
System.out.printf("Player 2: %d\n", player2List.get(i));
System.out.printf("It's a tie, cards return to your deck.\n");
}
if (player1List.isEmpty()){
System.out.printf("Player 2 wins the game.\n");
break;
}
if (player2List.isEmpty()){
System.out.printf("Player1 wins the game.\n");
break;
}
}
I have asked a similar question to this, however, this is more narrowed down to what I need.