1

I want to print the word which is containing maximum number of vowel. But Problem is that last word of sentence which is containing maximum number is not print. please help me solve that problem. My code is below. When i enter input 'Happy New Year', Output is 'Yea' .But i want i output is '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);
    }
}
Mihir Kekkar
  • 528
  • 3
  • 11
Susant
  • 87
  • 2
  • 9

1 Answers1

2

You cut words at spaces (correct), but you also cut at the last character, even if it's not a space (so this character is never dealt with). And that's not correct.

Here is a possibility:

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