繁体   English   中英

检查字符串数组中的元音

[英]Checking vowels in string array

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

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”的值有人知道为什么吗?

代码工作正常,检查arrayInput是否不为空/是,然后添加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"
   -      -        -  -          -

break; 每个case块之后的语句。 因为您希望计数,但是如果case语句到达,它将继续执行并计算其他情况。 但是您的案件永远不会达成。 因此有错误的条件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM