【问题标题】:Method miscalculates number of vowels方法错误计算了元音的数量
【发布时间】:2013-08-26 11:59:06
【问题描述】:

我的作业要求我读取文件并打印每行中元音的数量。出于某种奇怪的原因,它在某些行中打印了适量的元音,但在其他行中却没有。为什么要这样做?!

这是我计算元音的方法:

public static int calculateVowels(String line) 
{
    char[] vowels = new char[] {'a','e','i','o','u'};

    // count the number of vowels in a line
    int vowelCount = 0;
    for (int i = 0; i < line.length(); i++) {
        char a = line.charAt(i);
        for (char vowel : vowels) {
            if (a == vowel){
                vowelCount++;
                break;
            }
        }
    }
    return vowelCount;
}

这是我在 main 中调用它的时候:

while ((line = br2.readLine()) != null) 
{
    lineCount++;
    // count the number of words in a line
    String[] words = line.split(" ");
    if (words != null)
    wordCount += words.length;

    int vowelCount = calculateVowels(line);
    System.out.println("Line " + lineCount + " has " + vowelCount + " vowels.");
}

有什么想法吗?!谢谢!

【问题讨论】:

    标签: java variable-assignment


    【解决方案1】:

    您只计算小写元音。我的猜测是,计数在包含以元音开头的句子/大写单词的行中是关闭的。你可以使用这个测试:

    Character.toLowerCase(a) == vowel
    

    【讨论】:

    • 有没有一种简单的方法来计算两者而不用写所有的大写元音?
    • 使用这个字符串方法:.compareToIgnoreCase(String);
    • 'str.compareToIgnoreCase(string)' VS 'Character.toLowerCase(string)' 有什么区别吗?
    • @SrinathGanesh 你的签名错了:它是Character.toLowerCase(char),这是要点:如果你对字符进行操作,那么就使用它;如果您有字符串,请使用String#equalsIgnoreCase
    猜你喜欢
    • 1970-01-01
    • 2015-05-16
    • 2011-09-05
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 2014-10-20
    • 2021-01-31
    • 1970-01-01
    相关资源
    最近更新 更多