'StringIndexOutOfBoundsException when trying to count 'a's in the entered word in Java
public class methods {
public static int howMany(String word) {
char character = 'a';
int a = 0;
for (int i=0;i<=word.length();i++) {
if (word.charAt(i)==character) {
a++;
}
}
return a;
}
public static void main(String[] args) {
System.out.println(howMany("afdfaf"));
}
}
code gives error. please help. I couldn't find where is the error.
Expected output:
2
Observed error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6
The exception happens in this line:
if (word.charAt(i)==character) {
Solution 1:[1]
Change this line, you are exceeding the word length
Rewrite:
for (int i=0;i<=word.length();i++)
into
for (int i=0;i<word.length();i++)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Stultuske |