The immediate problem is due to you using <= temp.length()
instead of < temp.length()
. However, you can achieve this a lot more simply. Even if you use the string approach, you can use:
String temp = Integer.toString(guess);
int[] newGuess = new int[temp.length()];
for (int i = 0; i < temp.length(); i++)
{
newGuess[i] = temp.charAt(i) - '0';
}
You need to make the same change to use < newGuess.length()
when printing out the content too – otherwise for an array of length 4 (which has valid indexes 0, 1, 2, 3) you’ll try to use newGuess[4]
. The vast majority of for
loops I write use <
in the condition, rather than <=
.