在java中打印元音数量最多的单词

我想打印包含最大元音数的单词。但问题是包含最大数量的句子的最后一个单词没有打印。请帮我解决这个问题。我的代码如下。当我输入输入时'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);

    }

}


素胚勾勒不出你
浏览 131回答 1
1回答

慕田峪9158850

您可以在空格处剪切单词(正确),但也可以在最后一个字符处剪切,即使它不是空格(因此永远不会处理该字符)。这是不正确的。这是一种可能性:import java.util.Scanner;public class Abcd {&nbsp; &nbsp; public static void main(String args[]) {&nbsp; &nbsp; &nbsp; &nbsp; Scanner sc = new Scanner(System.in);&nbsp; &nbsp; &nbsp; &nbsp; System.out.print("Enter the sentence : ");&nbsp; &nbsp; &nbsp; &nbsp; String sentence = sc.nextLine();&nbsp; &nbsp; &nbsp; &nbsp; String wordMostVowels = "";&nbsp; &nbsp; &nbsp; &nbsp; int maxVowelCount = 0;&nbsp; &nbsp; &nbsp; &nbsp; for (String word : sentence.split(" ")) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int vowelCount = 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (char c : word.toLowerCase().toCharArray()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; vowelCount++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (vowelCount > maxVowelCount) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; maxVowelCount = vowelCount;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; wordMostVowels = word;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("The word with the most vowels (" + maxVowelCount + ") is: " + wordMostVowels);&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java