-1

I don't why it keeps giving me String index out of bounds exception.

int correctCount = 0;
for (int i = 0; i <= word.length(); i++) {
    if (playerGuesses.contains(word.charAt(i))) {
        System.out.print(word.charAt(i));
        correctCount++;
    } else {
        System.out.print("-");
    }
}
System.out.println();

return (word.length() == correctCount);
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Sen Rai
  • 21
  • 4
    Think about what the max index of any array/string/list is. Then look at the condition in your `for` loop. – Slaw Apr 18 '23 at 18:24
  • 1
    Q: String index out of bounds exception in Java. I don't know what to do. A: The character positions in a Java string are [zero-based](https://en.wikipedia.org/wiki/Zero-based_numbering). The first character is `word.charAt(0)`; the LAST character is `word.charAt(word.length() - 1)`. So your loop needs to be `i < word.length()`, not "<=". NOTE: You're correctly *STARTING* the loop at zero. You're just accessing one element too far - hence the exception. – paulsm4 Apr 18 '23 at 18:36

3 Answers3

2

Arrays starts at the 0th index so when you try to get the index of the list length here int i = 0; i <= word.length();i++, you're 1 slot out of bound.

This should work:

int correctCount = 0;
    for(int i = 0; i < word.length();i++) {
        if(playerGuesses.contains(word.charAt(i))) {
            System.out.print(word.charAt(i));
            correctCount++;
        }
        else {
            System.out.print("-");
        }
    }
    System.out.println();

    return(word.length() == correctCount);
Ramy M. Mousa
  • 5,727
  • 3
  • 34
  • 45
0

String / Char Arrays are zero-based.

HelloWorld is 10 characters, but as an array we see it as:

H,e,l,l,o,W,o,r,l,d
0,1,2,3,4,5,6,7,8,9

Each character becomes an iteration of the loop.

When you use i = 0; i <= word.length it is the same as i <= 10.

Since the array is zero-based, the "less than or equal to" actually creates 11 iterations of the loop when we only have 10. We only have 10 characters or iterations, we cannot have 11. The first iteration value is "H" at array position 0 str[0] hence declaring i = 0;

The last value is "d" at array position 9 str[9] at iteration 10. Position 10, on iteration 11, str[10] does not exist. It is out of bounds of the array.

You actually want i < 10 which would be i < word.length. Again, we want to stop at 1 short of 10 because the array is Zero-based.

geeves
  • 99
  • 2
  • 4
0

Yes, Java uses zero-based arrays, which means that when i == word.length(), i is exceeding the bounds of the value retrieved from word.length(). So you should use a less-than sign (<) in the for loop, and not a less-than-or-equal (<=).

for (int i = 0; i < word.length(); i++) {

Also, I highly recommend not using single-letter variable names. That's a great way to forget what's what.

Aaron
  • 55,518
  • 11
  • 116
  • 132