I am supposed to write a simple java application that counts each vowel in a string entered by the user and outputs the number of time each vowel occurs.
I don’t understand why my code is checking each individual word in my string. I am getting the right amount of vowels for each word. Here is what I have:
import java.util.Scanner;
public class VowelAnalyst
{
//
//
public static void main (String[] args)
{
String userString;
int aCount = 0, eCount = 0, iCount = 0, oCount = 0, uCount = 0;
char vowels;
Scanner scan = new Scanner (System.in);
System.out.println ("enter string:");
userString = scan.nextLine();
for (int count = 0; count < userString.length(); count++)
{
vowels = userString.charAt(count);
switch (vowels)
{
case 'a':
aCount++;
break;
case 'e':
eCount++;
break;
case 'i':
iCount++;
break;
case 'o':
oCount++;
break;
case 'u':
uCount++;
break;
default:
System.out.println ("Please enter valid string.");
}
System.out.println ("a: " +aCount);
System.out.println ("e: " +eCount);
System.out.println ("i: " +iCount);
System.out.println ("o: " +oCount);
System.out.println ("u: " +uCount);
}
}
}
May be you should move your below print statements out of your for loop, else they will print count after every character compared: –
UPDATE: –
Although the way you are doing is not a bad way, but you would be better if you maintain a
Map<Character, Integer>to store the count of eachVowel. You need to initialize your Map with an initial count of 0 for each character, and then on each character read, just increment the count, if match is found in Map.Here’s a sample snippet: –
And then your code of reading each character from string in for loop: –