Back to the Program-A-Day homepage
Problem
Your task is to write a program that takes a string of input from the user, and then count the number of vowels that are contained within this string. As output, provide the user with the final count of vowels, as well as the percentage of all characters in the string that these vowels represent. Repeat this until the user either cancels the input, or enters an empty string. For the purposes of this question, you may treat 'y' as though it is always a consonant (ie, just treat 'a', 'e', 'i', 'o', and 'u' as vowels).
|
|
String Methods and Debugging
|
Solution
I still have to do the solution write-up...
|
Code
Solution Code
import javax.swing.JOptionPane;
public class test
{
public static void main( String[] args )
{
String input; //input string
boolean done = false; //loop control variable
int vowelCount = 0; //our vowel count
//keep going until we're done
while( !done )
{
//get input from the user
input = JOptionPane.showInputDialog( "Enter a sentence:" );
if( input == null || input.equals( "" ) )
{
//user canceled, or gave no input -- we are done
done = true;
}
else
{
//convert all to lower case so we don't have to worry about upper vs lower case
input = input.toLowerCase();
for( int i = 0; i < input.length(); i++ )
{
//check if it's a vowel
if( input.charAt( i ) == 'a' || input.charAt( i ) == 'e'
|| input.charAt( i ) == 'i' || input.charAt( i ) == 'o'
|| input.charAt( i ) == 'u' )
{
vowelCount++; //increment vowel count
}
}
//output results
JOptionPane.showMessageDialog( null, "Vowel count: " + vowelCount + "\nVowel percentage: " +
vowelCount * 100 / input.length() + "%", "Vowel Counter", JOptionPane.INFORMATION_MESSAGE );
}
}
}
}
|
Back to the Program-A-Day homepage