gpt4 book ai didi

java从文本文件中读取元音

转载 作者:行者123 更新时间:2023-11-30 06:52:03 26 4
gpt4 key购买 nike

我正在创建一个从文本文件中读取元音的程序。文本是一个段落,我希望程序计算每个句子的元音。

这是一个例子7个元音

另一个3个元音

到目前为止,我已经编写了能够读取元音的代码。虽然,它把它当作一个额外的整体来读。在循环中,它将首先计数 7,然后第二行将其输出为 10。我希望它输出 7 作为第一行,输出 3 作为第二行。

我正在查看来自 java 的字符串 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.
*/

最佳答案

我创建了一个简单的类来实现我认为您的目标。 vowelTotal 重置,这样您就不会遇到您提到的句子元音相互添加的问题。我假设通过查看我的代码,您可以看到自己的解决方案?此外,此代码假定您将“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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com