StringIndexOutOfBoundsException 尝试计算 Java 中输入的单词中的 'a'

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"));
    }
}

代码出错。 请帮忙。 我找不到错误在哪里。

预期输出:

2

观察到的错误:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6

异常发生在这一行:

    if (word.charAt(i)==character) {

更改此行,您超出了字长

重写:

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

进入

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