我试图在用户输入的句子中找到元音最多的单词。现在,当我调用这个方法时,它可以用较短的句子很好地工作。但是当它超过 7 个单词时,它不会打印出元音最多的单词。我似乎无法发现错误=(
先谢谢你们了!
private static void getWordMostVowel(String sentence) {
String word = "";
String wordMostVowel = "";
int temp = 0;
int vowelCount = 0;
char ch;
for(int i = 0; i < sentence.length(); i++){
ch = sentence.charAt(i);
sentence = sentence.toLowerCase();
if (ch != ' '){
word = word + ch;
if ( ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' )
vowelCount++;
}
else {
if(vowelCount > temp){
temp = vowelCount;
wordMostVowel = word;
}
word = " ";
}
}
System.out.println("The word with the most vowels is: " + " " + wordMostVowel);
}
最佳答案
我建议一个不同的解决方案:不要尝试手动“构建”单词;这会给您的代码增加很多不必要的复杂性。
相反,请选择:
String words[] = sentence.split(" ");
上面创建了一个单词的数组(假设您的输入只是在每个单词之间使用空格)。
从那里您可以执行以下操作:
Set<Character> vowels = new HashSet<T>(Arrays.asList('a', 'e' ...));
上面创建了一个包含所有元音的集合。
现在:
for (String oneWord : words) {
int vowelCount = 0;
for (int i=0; i< oneWord.length; i++) {
if (vowels.contains(oneWorg.getCharAt(i))) {
vowelCount++;
}
}
}
上面遍历了每个单词;然后计算元音。内循环完成后,您就知道当前单词中的元音了。
对于最终的解决方案,您需要:
String theWordWithTheMostVowelsSoFar = "";
int maxVowelCountSoFar = 0;
当内部循环完成时,只需检查/更新这两个变量即可。我把这个作为练习留给读者,不要泄露所有的东西。
关于java - 元音最多的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40063011/