簡體   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