我的作业要求我读取一个文件,并打印每行中的元音数量。出于某种奇怪的原因,它在某些行中打印了适量的元音,但在其他行中却没有。它为什么这么做?!
以下是我计算元音的方法:
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;
}
当我把它称为时,它就在这里
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.");
}
有什么想法吗?!谢谢
您只计算小写元音。我的猜测是,包含以元音开头的句子/大写单词的行的计数是错误的。你可以使用这个测试:
Character.toLowerCase(a) == vowel