In: Computer Science
Instructions: Create a Java program that reads a string entered by the user and then determines and prints how many of each lowercase vowel (a, e, i, o, and u) appear in the entire string. Have a separate counter for each vowel. Also, count and print the number of non-vowel characters.
Example: User enters: "This house is beautiful."
a: 1
e: 2
i: 3
o: 1
u: 2
non-vowel:10
The Solution:
import java.util.Scanner; //for accepting input
public class Main
{
public static void main(String[] args) {
//inntializing variables for count n input
string
int aCount = 0, eCount = 0, iCount = 0;
int oCount = 0, uCount = 0, nonVowelCount = 0;
String userString;
//getting the string from user
Scanner sc = new Scanner (System.in);
System.out.println("Enter a string:");
userString = sc.nextLine();
for (int i = 0; i < userString.length(); i++) {
//reach each character of string and checking
char ch = userString.charAt(i);
if (ch== 'a') aCount++; //checking vowel 'a'
else if (ch== 'e') eCount++; //checking vowel 'e'
else if (ch== 'i') iCount++; //checking vowel 'i'
else if (ch== 'o') oCount++; //checking vowel 'o'
else if (ch== 'u') uCount++; //checking vowel 'u'
//checking non-vowels
else if ((ch >= 'a'&& ch <= 'z')||(ch >=
'A'&& ch <= 'Z')) nonVowelCount++;
}
//displaying the count of each vowel and non-vowels
System.out.println("a: " + aCount + "\n" +
"e: " + eCount + "\n" +
"i: " + iCount + "\n" +
"o: " + oCount + "\n" +
"u: " + uCount + "\n" +
"non-vowel:" + nonVowelCount);
}
}
The Screenshots:
The Code:
The Output: