'Getting IndexOutOfBounds exceptions with Arraylist in a Loop
I am making a game similar to Worldle.
I am trying append input to an Arraylist each time the loop executes.
While also trying to keep the format of wordle (testnum and testnum2). I am quite new to java and do not know why I am getting an IndexOutOfBoundsException.
My code:
import java.util.Scanner;
import java.util.Random;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
int i = 0;
int testnum = 6;
int testnum2 = 1;
int aaa = 0;
String guess;
ArrayList<String> inputs = new ArrayList<String>();
String[] wordList = { "CHARM", "UNITE","BRAVE", "ADIEU", "ROBOT", "FORGE" };
String randomWord = wordList[(int) (Math.random() * wordList.length)];
Scanner input = new Scanner(System.in);
for(int a=0; a<6; a++){ /*columns*/
for(int j=0; j<5; j++){ /*rows*/
System.out.print("- ");
}
System.out.println();
}
while(i<6) {
System.out.println("Enter Guess: ");
guess = input.nextLine();
for(int a=0; a<6; a++){ /*columns*/
for(int j=0; j<5; j++){ /*rows*/
System.out.print("- ");
}
System.out.println();
}
if(guess.toUpperCase().equals(randomWord)) {
System.out.println("Guessed");
i++;
break;
}
for(String hi : wordList) {
if(guess.toUpperCase().equals(hi)) {
inputs.add(guess);
i++;
System.out.print("Incorrect Guess. Tries Left: ");
System.out.println(6 - i);
for (int aa = 0; aa<testnum2; aa++) {
System.out.println(inputs.get(aaa));
aaa+=1;
}
testnum -=1;
testnum2 +=1;
for(int a=0; a<testnum; a++){ /*columns*/
for(int j=0; j<5; j++){ /*rows*/
System.out.print("- ");
}
System.out.println();
}
}
}
if(guess.length() < 5) {
System.out.println("Not enough letters. Please try again: ");
}
}
}
}
Solution 1:[1]
after some testing I found a solution.
My error was in
for (int aa = 0; aa<testnum2; aa++) {
System.out.println(inputs.get(aaa));
aaa+=1;
}
I changed it to:
for (int aa = 0; aa<testnum2; aa++) {
aaa = aa;
System.out.println(inputs.get(aaa));
}
The error was the aaa incremented after it got accessed, so I did it before and set it equal to aa.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rhoo123 |

