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



我正在尝试从 Java codingbat.com 完成这个练习。我在这几段代码上收到此错误"令牌"返回"上的语法错误,无效类型",我无法弄清楚原因。我正在尝试返回单词"hi"在给定字符串中出现的次数。谢谢!

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

问题是,在if条件(1)之后,您有一个;而不是{,这基本上意味着if体是空的。反过来,count++行 (2) 之后的}被视为for循环的结束(而不是应有的if),而应结束for循环的}将结束方法。

这使得您的return count;和最终}挂在类定义的中间,因为它不是有效的语法。

return count; 在方法之外,并且在if之后有一个不应该存在的;,在良好的缩进并删除此;之后,您将获得:

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 should be here
}   //Method countHI ends here
    return count;  //??
}

现在你明白为什么即使身体只包含一行,戴牙套也非常重要吗?

您在if()条件之后没有左括号。

if语句中的条件后面有一个分号。

 if(str.substring(i, i + 2).equals("hi"));

相关内容

最新更新