Reputation: 3
Hi guys while making a word-puzzle game, I came across a problem in double checking that the vertical and horizontal were both words from my current file that was saved to an arraylist.
String letterSize = "" + size;
makeLetterWordList(letterSize);
boolean finished = false;
while ( !finished ) {
finished = true;
for (int i = 0; i < size; i++) {
int randomYWord = randomInteger(wordList.size());
String item = wordList.get(randomYWord);
puzzleListY.add(item);
}
for (int i = 0; i <= puzzleListY.size(); i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j <= puzzleListY.size(); j++) {
sb.append(puzzleListY.get(j).charAt(j));
}
randomXWord = sb.toString();
if (!wordList.contains(randomXWord)) {
finished = false;
break;
} else {
puzzleListX.add(randomXWord);
}
}
}
The error Produced was as follows:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
I am struggling to find the mistake in my code can anyone assist me?
Upvotes: 0
Views: 9028
Reputation: 1607
Loop should be only till size - 1
for (int i = 0; i <= puzzleListY.size(); i++) { // remove =
For other loop as well, Since you are starting from index 0 and there are n elements loop should be from 0 to n-1
Upvotes: 2