检查字符串数组中的元音

时间:2013-11-15 21:29:38

标签: java arrays

这是我编写的用于计算字符串数组中元音量的代码:

int vowels = 0;
for (int x = 0; x < arrayInput.length; x++) {
    for (int a = 0; a < arrayInput[x].length(); a++){
        switch (arrayInput[x].charAt(a)){
            case 'A': vowels++;
            case 'a': vowels++;
            case 'E': vowels++;
            case 'e': vowels++;
            case 'I': vowels++;
            case 'i': vowels++;
            case 'O': vowels++;
            case 'o': vowels++;
            case 'U': vowels++;
            case 'u': vowels++;
            case 'Y': vowels++;
            case 'y': vowels++;
        }
    }
}

然而,元音总是返回0.为什么?

发现问题了! 该程序早期的代码:

String[] vowelArray = arrayInput;
for (int x = 0; x < vowelArray.length; x++) {
    vowelArray[x] = vowelArray[x].replaceAll("[AEIOUYaeiouy]", "_");
}
for (int x = 0; x < vowelArray.length; x++) {
    System.out.print(vowelArray[x] + " ");
}

正在改变`arrayInput'的值 有谁知道为什么?

2 个答案:

答案 0 :(得分:4)

代码工作正常,检查arrayInput是否为空/ null,是否添加break语句

    String[] arrayInput = {"This","is","random","string"};
    int vowels = 0;
    for (int x = 0; x < arrayInput.length; x++) {
        for (int a = 0; a < arrayInput[x].length(); a++){
            switch (arrayInput[x].charAt(a)){
                case 'A': vowels++;break;
                case 'a': vowels++;break;
                case 'E': vowels++;break;
                case 'e': vowels++;break;
                case 'I': vowels++;break;
                case 'i': vowels++;break;
                case 'O': vowels++;break;
                case 'o': vowels++;break;
                case 'U': vowels++;break;
                case 'u': vowels++;break;
                case 'Y': vowels++;break;
                case 'y': vowels++;break;
            }
        }
    }
    System.out.println(vowels);

输出

5

输入

"This"   "is"    "random"    "string"
   -      -        -  -          -

答案 1 :(得分:1)

在每个案例块之后放置break;语句。因为你想让vovels计数,但如果case语句到达它继续执行并计算其他情况。但你的情况从未达成。因此有错误的条件。

相关问题