我正在创建一个从文本文件中读取元音的程序。文本有一个段落长,我希望程序计算每个句子的元音数。
这是一个例子 7个元音
另一个 3个元音
到目前为止,我已经编写了能够读取元音的代码。尽管如此,它还是将其作为一个额外的整体来解读。在循环中,它将首先计数 7,然后第二行将其输出为 10。我希望它输出 7 作为第一行,3 作为第二行。
我正在查看 java 的 String API,但没有看到任何可以帮助解决此问题的内容。我目前计算元音的方法是使用 for 循环与 Charat() 进行循环。我是否遗漏了某些内容,或者没有办法阻止它读取并添加到计数器中?
这是一个例子
while(scan.hasNext){
String str = scan.nextLine();
for(int i = 0; i<str.length(); i++){
ch = str.charAt(i);
...
if(...)
vowel++;
}//end for
S.O.P();
vowel = 0;//This is the answer... Forgotten that java is sequential...
}
}// end main()
}//end class
/*output:
This sentence have 7 vowels.
This sentence have 3 vowels.
*/
最佳答案
我创建了一个简单的类来实现我认为您的目标。元音总数会重置,这样您就不会遇到您提到的句子元音相互叠加的问题。我假设通过查看我的代码,您可以看到您自己的解决方案?另外,此代码假设您包含“y”作为元音,并且还假设句子以正确的标点符号结尾。
public class CountVowels{
String paragraph;
public CountVowels(String paragraph){
this.paragraph = paragraph;
countVowels(paragraph);
}
int vowelTotal = 0;
int sentenceNumber = 0;
public void countVowels(String paragraph){
for(int c = 0; c < paragraph.length(); c++){
if( paragraph.charAt(c) == 'a' || paragraph.charAt(c) == 'e' || paragraph.charAt(c) == 'i' || paragraph.charAt(c) == 'o' || paragraph.charAt(c) == 'u' || paragraph.charAt(c) == 'y'){
vowelTotal++; //Counts a vowel
} else if( paragraph.charAt(c) == '.' || paragraph.charAt(c) == '!' || paragraph.charAt(c) == '?' ){
sentenceNumber++; //Used to tell which sentence has which number of vowels
System.out.println("Sentence " + sentenceNumber + " has " + vowelTotal + " vowels.");
vowelTotal = 0; //Resets so that the total doesn't keep incrementing
}
}
}
}
关于java从文本文件中读取元音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39693136/