Write a program in Java to input a String and print that word which contains the highest number of vowels.
Example -
input - HAPPY NEW YEAR
output - YEAR
Don't Spam!!!
Answers
Answer:
Here's it:
Explanation:
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter The String: ");
String sentence = sc.nextLine();
String word = "";
String wordMostVowel = "";
int abc = 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 > abc) {
abc = vowelCount;
wordMostVowel = word;
}
word = "";
vowelCount = 0;
}
}
System.out.println("The word with the highest number of vowels is: " + " " + wordMostVowel);
}
}
Required Answer:-
Question:
- Write a program in Java to input a string and print. the word which contains the highest number of vowels.
Solution:
Here is the program.
- import java.util.*;
- public class HighestVowels {
- public static void main(String[] args) {
- Scanner sc=new Scanner(System.in);
- System.out.print("Enter: ");
- String s=sc.nextLine();
- String a[]=s.split(" ");
- int highestVowels=0;
- String result="";
- for(int i=0;i<a.length;i++)
- {
- int countVowel=countVowels(a[i]);
- if(countVowel>highestVowels)
- {
- highestVowels=countVowel;
- result=a[i];
- }
- }
- System.out.println("Word with highest Vowels is: "+result);
- sc.close();
- }
- static int countVowels(String s)
- {
- int c=0;
- s=s.toLowerCase();
- for(int i=0;i<s.length();i++)
- {
- char ch=s.charAt(i);
- if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
- c++;
- }
- return c;
- }
- }
Explanation:
- We will ask the user to enter the sentence. We will split the sentence and store the words in an array. This can be achieved by using split() function. A word is started and ended with space. So, we will split the string at the places where it contains spaces. Now, the words are stored in an array.
- Now, to find the string with highest number of variables, we will first assume that the highest number of vowels present is zero. Now, we will calculate number of vowels present in each word. If number of vowels present in the word is greater than the maximum value, we will initialise the maximum value and store the word in result variable. Now, the word will be displayed on the screen.
- I have created a function that counts the number of vowels present in a given string.
Output is attached.