猿问

如何计算一个字母在数组的所有字符串中出现的次数?

public static int countLetter(String[] x, String y){

    int count = 0;

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

        for(int h = 0; h < x[i].length(); h++){

            String yo = new String(x[i].substring(h,h+1));

            if(yo==y){

                count++;}

            }

        }

        return count;

    }

}

我的方法应该返回一个整数,该整数计算字母在数组的所有字符串中出现的总次数。(假设字符串是一个字母,我不能使用 charAt())。


慕盖茨4494581
浏览 226回答 2
2回答

慕斯709654

您可以在第 6 行更改代码if(yo==y)到if(yo.equals(y))

森林海

问题在于字符串比较。您需要使用equals()或者可能equalsIgnoreCase()在比较 Java 中的 2 个字符串时:public static int countLetter(String[] x, String y) {&nbsp; &nbsp;int count = 0;&nbsp; &nbsp;for (int i = 0; i < x.length; i++) {&nbsp; &nbsp; &nbsp; for (int h = 0; h < x[i].length(); h++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;String yo = new String(x[i].substring(h, h + 1));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (yo.equals(y)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; count++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;}&nbsp; &nbsp;return count;}你也可以用一个char代替String:public static int countLetter(String[] x, char y) {&nbsp; &nbsp;int count = 0;&nbsp; &nbsp;for (int i = 0; i < x.length; i++) {&nbsp; &nbsp; &nbsp; for (int h = 0; h < x[i].length(); h++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (x[i].charAt(h) == y) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; count++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;}&nbsp; &nbsp;return count;}
随时随地看视频慕课网APP

相关分类

Java
我要回答