【问题标题】:print the word which has maximum number of vowel in java打印java中元音最多的单词
【发布时间】:2019-08-31 14:23:45
【问题描述】:

我想打印包含最多元音的单词。但问题是包含最大数量的句子的最后一个单词没有打印出来。请帮我解决这个问题。我的代码如下。 当我输入输入'Happy New Year' 时,输出为'Yea'。但我希望我的输出为'Year'

import java.util.Scanner;
public class Abcd {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter The Word : ");
        String sentence = sc.nextLine();
        String word = "";
        String wordMostVowel = "";
        int temp = 0;
        int vowelCount = 0;
        char ch;
        for (int i = 0; i < sentence.length(); i++) {
            ch = sentence.charAt(i);
            if (ch != ' ' && i != (sentence.length() - 1)) {
                word += ch;  
                ch = Character.toLowerCase(ch);
                if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
                    vowelCount++; 
                }
            } else { 
                if (vowelCount > temp) {
                    temp = vowelCount;
                    wordMostVowel = word;
                }
                word = "";
                vowelCount = 0;
            }    
        }
        System.out.println("The word with the most vowels (" + temp + ") is: " + " " + wordMostVowel);
    }
}

【问题讨论】:

标签: java


【解决方案1】:

你在空格处剪切单词(正确),但你也在最后一个字符处剪切,即使它不是空格(所以这个字符永远不会被处理)。这是不正确的。

这是一种可能性:

import java.util.Scanner;

public class Abcd {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the sentence : ");
        String sentence = sc.nextLine();
        String wordMostVowels = "";
        int maxVowelCount = 0;

        for (String word : sentence.split(" ")) {
            int vowelCount = 0;
            for (char c : word.toLowerCase().toCharArray()) {
                if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
                    vowelCount++;
                }
            }

            if (vowelCount > maxVowelCount) {
                maxVowelCount = vowelCount;
                wordMostVowels = word;
            }
        }

        System.out.println("The word with the most vowels (" + maxVowelCount + ") is: " + wordMostVowels);
    }
}

【讨论】:

  • 感谢您解决了这个问题 Jean-Claude Arbaut
猜你喜欢
  • 2013-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-15
  • 2013-01-21
  • 1970-01-01
  • 2023-03-25
相关资源
最近更新 更多