令牌"return"上的语法错误,类型无效?

Jos*_*ant 0 java syntax

我正在尝试用Java编写来自codingbat.com的练习.我得到这个错误"令牌上的语法错误"返回",无效的类型"在这一小段代码上,我无法弄清楚为什么.我试图返回单词"hi"出现在给定String中的次数.谢谢!

public int countHi(String str) {
    int count = 0;
    for(int i = 0; i < str.length() - 1; i++){
        if(str.substring(i, i + 2).equals("hi"));
            count++;
        }
    }
    return count;
}
Run Code Online (Sandbox Code Playgroud)

Ant*_*ist 5

public int countHi(String str) {
    int count = 0;
    for(int i = 0; i < str.length() - 1; i++){
        if(str.substring(i, i + 2).equals("hi")); // 1
            count++;
        } // 2
    }
    return count;
}
Run Code Online (Sandbox Code Playgroud)

问题是你有一个;而不是{你的if条件(1),这实际上意味着if身体是空的.的}count++线(2),反过来,视为的端for环(而不是if因为它应该是),并且}应该结束for循环,而不是结束该方法.

这使得你的return count;最后一个}挂在类定义的中间,它不是有效的语法.