I am writing a program where the user inputs a sentence, then the program counts the total vowels, letters, and characters.
I have everything done but not only do I have to count the total vowels, I have to display each vowel with the total number in the sentence.
This is my code - I have 3 different ways I came up with to count the total number of vowels in the sentence. I'm just not sure which will be the easiest to use in order to count each vowel letter itself.
public class CountVowels {
public static void main(String[] args) {
String input;
char ch;
int letA = 0, letE = 0, letI = 0, letO = 0, letU = 0;
input = JOptionPane.showInputDialog("Input a sentence.");
int length = input.length();
char[] characters = input.toCharArray();
int vowelCount = 0;
for (int i = 0; i < characters.length; i++)
{
ch = input.charAt(i);
if ( (ch == 'A') || (ch == 'a')
|| (ch == 'E') || (ch == 'e')
|| (ch == 'I') || (ch == 'i')
|| (ch == 'O') || (ch == 'o')
|| (ch == 'U') || (ch == 'u') )
vowelCount++;
}
}
int letters = 0;
for (int i = 0; i < characters.length; i++)
{
if (Character.isLetter(characters[i]))
letters++;
}
System.out.println(input);
System.out.println(" ");
System.out.println("Vowel\t\tNumber");
**** This is where I have to list each letter with the number ****
System.out.println("The total number of vowels in the sentence: " + vowelCount);
System.out.println("The total number of letters in the sentence: " + letters);
System.out.println("The total number of characters in the sentence: " + length);
}
}
This is the second way I could use to count vowels
int vowels = 0;
for (int i = 0; i < characters.length; i++){
if (characters[i] == 'a' || characters[i] == 'e' || characters[i] == 'i' || characters[i] == 'o' || characters[i] == 'u')
vowels++;
And finally, this is the third way I have..
for (char c : input.toCharArray())
{
switch(c){
case 'A':
case 'a':
break;
case 'E':
case 'e':
break;
case 'I':
case 'i':
break;
case 'O':
case 'o':
break;
case 'U':
case 'u':
break;
default: vowelCount++;
}
}
Can anyone tell me which will be the best one to use and how I go about counting each vowel letter? I'm assuming I will use a for loop but I don't really know how to go about doing that with this type of program and I don't know where I would place it if that is what I use.
Thanks in advance for any help!


Sign In
Create Account

Back to top









