An IndexOutOfBondsException appears whenever you try to access the empty or non-allocated index of any array (char[]
, int[]
, ...). Here is a great example for your case.
// Your array contains 5 elements
char[] arr = new char[] {'a', 'b', 'c', 'd', 'e'};
// Then, you invoke an element that doesn't exist in an array
System.out.println(arr[5]); // This invoking will throw an IndexOutOfBondsException
// Even you invokes like this
System.out.println(arr[-1]); // Not exist
System.out.println(arr.size()); // Because the size is 5
Now staring at your code, it is a little bit ambiguous because the guess variable is an unknown type. Assume guess
is a String and you are trying to put a guess
as a String into a getters
. Then you set a guess
value as an inputted value. This thing is ambiguous and causes a wrong logic code and the getters
still be an empty array (or not contain 6 elements).
SOLUTION
In order to solve it, you need to put the line char[] getters = guess.toCharArray();
below guess = in.nextLine();
. It means, that after taking a guess value from the user, you create an array that contains a guess character. Here is an instance of what I describe:
char[] letters = winner.toCharArray();
// Take value from input
for (int q = 0; q < 6; q++) {
System.out.println("Please enter a 5 letter guess:");
guess = in.nextLine();
}
// Then put it into a getters array
char[] getters = guess.toCharArray();
// Trying to compare
for (int i = 0; i < 6; i++) {
if (letters[i] == getters[i]) {
soFar = soFar + "||" + getters[i] + "||";
} else {
soFar = soFar + getters[i];
}
}