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)
You're increasing
d
inside the loop, which you shouldn't - just let thefor
loop do it's thing. Also, you should terminate the loop with<
, not<=
:But frankly, you could just stream the characters in the string for a much more elegant solution: