我有这段代码可以检查字母a,b,c,d等是否是单词中的第一个字母(在代码中称为“苹果”)。然后,它存储以每个字母开头的单词数。我正在尝试简化我的代码,也许就像使用for循环或数组,但是我不确定该如何做。

int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0, i = 0, j = 0, k = 0, l = 0, m = 0, n = 0, o = 0, p = 0, q = 0, r = 0, s = 0, t = 0, u = 0, v = 0, w = 0, x = 0, y = 0, z = 0;

if(apple.length() > 0)
{
    if (apple.charAt(0) == 'a') {
        a++;
    }
    else if (apple.charAt(0) == 'b') {
        b++;
    }
    else if (apple.charAt(0) == 'c') {
        c++;
    }
    else if (apple.charAt(0) == 'd') {
        d++;
    }
    .
    .
    .
    else if (apple.charAt(0) == 'x') {
        x++;
    }
    else if (apple.charAt(0) == 'y') {
        y++;
    }
    else if (apple.charAt(0) == 'z') {
        z++;
    }
}

System.out.println("The number of words that start with a - " + a);
System.out.println("The number of words that start with b - " + b);
System.out.println("The number of words that start with c - " + c);
System.out.println("The number of words that start with d - " + d);
.
.
.
System.out.println("The number of words that start with x - " + x);
System.out.println("The number of words that start with y - " + y);
System.out.println("The number of words that start with z - " + z);

最佳答案

public static void main(String[] args) {

        String apple = "apple";
        int[] arr = new int[26];
        String matchStr = "abcdefghijklmnopqrstuvwxyz";
        char[] charArr = matchStr.toCharArray();

        for(int i = 0 ; i < arr.length ; i ++) {
            if(apple.startsWith(charArr[i] + "")) {
                arr[i]+= 1;
            }
        }

        for(int i = 0 ; i < charArr.length ; i ++) {
            System.out.println("The number of words that start with " + charArr[i] + " - " + arr[i]);
        }
    }

08-05 21:06
查看更多