为什么 if 条件中的 equals() 允许所有内容?

我的任务是创建函数,如果字符串参数包含 1,2 或 3 个“e”字符,则返回 true,需要 for 循环。看起来 equals() 方法将所有内容都传入并在 sLetter = "e" 与否时增加计数器。或者也许问题出在其他地方?


static boolean checkLetter (String paramOne){

    int count = 0;

    for (int i = 0; i <= paramOne.length() - 1; i++) {

        char letter = paramOne.charAt(i);

        String sLetter = Character.toString(letter);


        if (sLetter.equals("e"));

        {

            count++;

        }

    }


    System.out.print((count >= 1) && (count <= 3));

    return (count >= 1) && (count <= 3);

}


宝慕林4294392
浏览 204回答 2
2回答

饮歌长啸

删除 if 语句末尾的分号。static boolean checkLetter (String paramOne){&nbsp; &nbsp; int count = 0;&nbsp; &nbsp; for (int i = 0; i <= paramOne.length() - 1; i++) {&nbsp; &nbsp; &nbsp; &nbsp; char letter = paramOne.charAt(i);&nbsp; &nbsp; &nbsp; &nbsp; String sLetter = Character.toString(letter);&nbsp; &nbsp; &nbsp; &nbsp; if (sLetter.equals("e"))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; count++;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; System.out.print((count >= 1) && (count <= 3));&nbsp; &nbsp; return (count >= 1) && (count <= 3);}

有只小跳蛙

你有一个额外的分号“;” 在 if 语句上,所以如果它为真并且计数总是上升,则不会发生任何事情改变&nbsp;if (sLetter.equals("e"));&nbsp;{&nbsp; &nbsp;count++;&nbsp;}到&nbsp;if (sLetter.equals("e")) {&nbsp; &nbsp;count++;&nbsp;}你也可以通过做来简化逻辑if (letter == 'e') {&nbsp; &nbsp;count++;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java