Write a program to take a String as input then display the word which has highest number of vowels.
For example:
Enter a String
EDUCATION IS important
EDUCATION has highest number of vowels
2nd e.g.
Enter a String
Hello use dog
Hello and use has same highest number of vowels
import java.util.*;
class App {
static int countNumberVowelsInWord(String word) {
int count = 0;
for (int i = 0; i < word.length(); i++) {
if (word.toLowerCase().charAt(i) == 'a' || word.toLowerCase().charAt(i) == 'e'
|| word.toLowerCase().charAt(i) == 'i' || word.toLowerCase().charAt(i) == 'o'
|| word.toLowerCase().charAt(i) == 'u') {
count++;
}
}
return count;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a String: ");
String inputWords[] = in.nextLine().split(" ");
int counters[] = new int[inputWords.length];
int maxVowels = 0;
for (int i = 0; i < inputWords.length; i++) {
counters[i] = countNumberVowelsInWord(inputWords[i]);
if (counters[i] > maxVowels) {
maxVowels = counters[i];
}
}
int count = 0;
for (int i = 0; i < inputWords.length; i++) {
if (counters[i] == maxVowels) {
count++;
}
}
if (count == 1) {
for (int i = 0; i < inputWords.length; i++) {
if (counters[i] == maxVowels) {
System.out.print(inputWords[i]);
}
}
System.out.print(" has highest number of vowels");
} else {
for (int i = 0; i < inputWords.length; i++) {
if (counters[i] == maxVowels) {
System.out.print(inputWords[i]);
if (count > 1) {
System.out.print(" and ");
}
count--;
}
}
System.out.print(" has same highest number of vowels");
}
in.close();
}
}
Comments
Leave a comment