【问题标题】:Checking vowels in string array检查字符串数组中的元音
【发布时间】:2013-11-15 21:29:38
【问题描述】:

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

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' 的值 有谁知道为什么?

【问题讨论】:

  • 您需要在每个案例之后使用breakdocs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
  • 请显示您的String数组的内容。
  • 我昨天发布了this answer。你应该检查一下。
  • 你应该打印arrayInput[x]的包含以确保它不为空。
  • 你是什么意思 - “正在改变 `arrayInput' 的值有人知道为什么吗?” ?? OP 也代表 Original Poster。

标签: java arrays


【解决方案1】:

代码工作正常,检查arrayInput 是否不为空/null 并且是添加中断语句

    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"
   -      -        -  -          -

【讨论】:

    【解决方案2】:

    在每个 case 块之后放置 break; 语句。因为您希望元音计数,但如果 case 语句到达它继续执行并计算其他情况。但是你的案子永远没有达成。从而有错误的条件。

    【讨论】:

    • 如果是这样,那他肯定不会得0了吧?
    • @AnkitRustagi 不,不可能像你那样做。
    猜你喜欢
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    • 2019-02-26
    • 2016-06-11
    • 1970-01-01
    相关资源
    最近更新 更多