StringIndexOutOfBoundsException in a counting loop in Java

258 Views Asked by At

I have to write a code for class using Java in which the number of occurrences of the letter E is counted and printed out (both cases included). This is what I have.

String sVerse = "As we enter our centennial year we are still young ";

System.out.println(sVerse);

int len3 = sVerse.length();
int countE = 0;

for (int d = 0; d <= len3; d++){
    char e = sVerse.charAt(d);
    d = d + 1;

    if (e == 'e' || e == 'E')
    {
        countE = countE + 1;
    }
    else
    {
        countE = countE;
    }
}

System.out.println(countE);

The code runs, and the string prints, but after the string prints I get this error:

 java.lang.StringIndexOutOfBoundsException: String index out of range: 1258
    at java.lang.String.charAt(Unknown Source)
    at Unit4plus.main(Unit4plus.java:125)
3

There are 3 best solutions below

1
On

You're increasing d inside the loop, which you shouldn't - just let the for loop do it's thing. Also, you should terminate the loop with <, not <=:

int countE = 0;
for (int d = 0; d < len3; d++) {
    char e=sVerse.charAt(d);

    if (e=='e' || e=='E') {
        countE++;
    }
}

But frankly, you could just stream the characters in the string for a much more elegant solution:

long countE = sVerse.chars().filter(c -> c == 'e' || c == 'E').count();
2
On

Your condition in the first loop should be :

d < len3

Since length starts at 1 but index of characters in your string are 0 based.

Moreover, your statement d=d+1 in the for loop is useless and makes you iterate 2 by 2 since you already increment it in the for loop with

d++
0
On

You need to change the condition for the loop since the length is +1 of the maximum index.You also increase the value of the variable "d" two times, one in the definition of the "for" loop, and the other is inside it. Try replace it with this code:

        String sVerse = "As we enter our centennial year we are still young";
        int len3 = sVerse.length();
        int countE = 0;
        for (int d = 0; d < len3; d++) {
            char e = sVerse.charAt(d);
            if (e == 'e' || e == 'E')
                countE++;
        }
        System.out.println(countE);