Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Counting Vowels and Consonants...

807605Oct 2 2007 — edited Oct 2 2007
Hellos All,

I have the following
import java.util.Scanner;

public class r3
{
public static void main(String[] args)
{

//declare variables
String userInput, workString = "";
int stringLength;
int numberVowels = 0;
char userChoice;
Scanner keyboard = new Scanner(System.in);
char[] vowelArray = {'a', 'e', 'i', 'o', 'u'};
boolean enterAString;

System.out.println("Would you like to enter a string");
enterAString = keyboard.nextBoolean();


//user input

while(enterAString)
{//begin loop
System.out.println("please enter a string");
userInput = keyboard.nextLine();
userInput = userInput.toLowerCase();
stringLength = userInput.length();

for(int i = 0; i < stringLength; ++i)
{
if((int)userInput.charAt(i) >= 97 && (int)userInput.charAt(i) <=122)
workString = workString + userInput.charAt(i);

}
/*

for(int i = 0; i < stringLength; ++i)
{
if(userInput.charAt(i) >= 'a' && userInput.charAt(i) <= 'z')
workString = workString + userInput.charAt(i);

}
*/
System.out.println(workString);

System.out.println("Please select\n"
+"a for number of vowels\n"
+"b for number of consonents\n"
+"c for number of vowels and consonents\n"
+"d to enter another string\n"
+"e to exit\n");


userChoice = ((keyboard.nextLine()).toLowerCase()).charAt(0);

System.out.println(userChoice);


//determin number of vowels
for(int i = 0; i < workString.length(); ++i)
for(int j = 0; j < vowelArray.length; ++j)
if(workString.charAt(i) == vowelArray[j])
numberVowels++;



switch(userChoice)
{
case 'a':
System.out.println("The number of vowels is: " + numberVowels);
break;
case 'b':
System.out.println("The number of consonents is: " + (workString.length() - numberVowels));
break;

case 'c':
System.out.println("The number of vowels and consonents is: " + workString.length());
break;

case 'd':
break;
case 'e':
enterAString = false;
break;
default:
System.out.println("Invalid input. Goodby.");
}//end switch

}//end loop

System.out.println("Thanks for playing");


}//end main
}//end class
So far it somewhat works fine, but for the number of consonents when printed. The number printed out is not equal to the string input by the user. The bigger the string gets the bigger the difference in the amount of consonants.

any help would be appretiated thanks
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Oct 30 2007
Added on Oct 2 2007
1 comment
155 views