stephen vaye stephen vaye - 1 year ago 61
Java Question

Reading # of vowels from String in java

there. I need some assistance. I'm working on having the user input text, reverse the text, then read the number of vowels in the text and tell them how many vowels were in the reversed text.

public static void main(String[] args)
System.out.println ("Please type in whatever you want ");
Scanner type_input = new Scanner (;
Scanner type_input = new Scanner (;
StringBuilder type_output = new StringBuilder();
System.out.println("Is this what you types in? " + type_output);

for(int vowel_num = 0; vowel_num< type_hold.length(); vowel_num++)
if((type_hold.charAt(vowel_num) =='a')||(type_hold.charAt(vowel_num) =='e')||
(type_hold.charAt(vowel_num) =='o')||(type_hold.charAt(vowel_num) =='i')||
(type_hold.charAt(vowel_num) =='u')){

System.out.println("There are " + vowel_num + " vowels in " + type_hold);

But when I get it to typing in to running it i get the following. I'm not sure where I'm messing up.

Please type in whatever you want
Is this what you types in? olleh
There are 1 vowels in hello
There are 4 vowels in hello

Edit: I figured it out. Thank you to everyone for the help!

Answer Source
  1. What is type_hold? Didn't see you instantiate it, and you are using it.
  2. What vowel_num? The index you are looping through the string? or the number of vowels you have counted?

What you should have done to count vowels in a string:

Assuming vowel_index is the index, vowel_num is the count of vowels you have encountered.

int vowel_num = 0;
for(int vowel_index = 0; vowel_index < type_hold.length(); vowel_index++) {
    if((type_hold.charAt(vowel_index) =='a') || 
       (type_hold.charAt(vowel_index) =='e') || 
       (type_hold.charAt(vowel_index) =='o') || 
       (type_hold.charAt(vowel_index) =='i') || 
       (type_hold.charAt(vowel_index) =='u')){

         // character at vowel_index is a vowel.
         // you have encountered 1 more vowel! 
         System.out.println("Character at " + vowel_index + " is a vowel.");
         vowel_num ++;

System.out.println("There are " + vowel_num + " vowels in " + type_hold);