元音最多的单词 [英] word with the most vowels

查看:200
本文介绍了元音最多的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找用户输入的句子中元音最多的单词.现在,当我调用此方法时,它可以用较短的句子正常工作.但是当它超过7个单词时,并不会打印出具有最多元音的单词.我似乎无法发现错误=(

I am trying to find a word with the most vowels in a sentence inputted by the user. Right now when I call this method it works fine with a shorter sentence. But when it gets over 7 words it doesn't print out the word with the most vowels. I can't seem to spot the error =(

我先谢谢你们!

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);

}

推荐答案

我建议使用另一种解决方案:不要尝试手动构建"单词;这会给您的代码增加很多不必要的复杂性.

I suggest a different solution: don't try to "build" the words manually; that adds a lot of unnecessary complexity to your code.

取而代之的是:

String words[] = sentence.split(" ");

以上内容为您的单词创建了一个数组(假设您的输入仅在每个单词之间使用空格).

The above creates an array of your words (assuming that your input simply uses spaces between each word).

从那里您可以执行以下操作:

From there you can do something like:

Set<Character> vowels = new HashSet<T>(Arrays.asList('a', 'e' ...));

上面创建了一个包含所有元音的集合.

The above creates a set that contains all vowels.

现在:

for (String oneWord : words) {
  int vowelCount = 0;
  for (int i=0; i< oneWord.length; i++) {
    if (vowels.contains(oneWorg.getCharAt(i))) { 
      vowelCount++;
    }
  }
}

以上内容遍历了每个单词;然后计算元音.内循环完成后,您将知道当前单词中的元音.

The above walks through each word; to then count the vowels. After the inner loop has finished, you know the vowels in the current word.

对于最终解决方案,您需要:

For the final solution, you would need:

String theWordWithTheMostVowelsSoFar = "";
int maxVowelCountSoFar = 0;

当内循环完成后,只需检查/更新这两个变量.我把它留给读者作为练习,不要把所有的东西都丢掉.

Simply check/update those two variables when the inner loop has finished. I leave that as exercise to the reader to not give all the things away.

这篇关于元音最多的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆