I'm trying to make a program that counts the number of vowels in a sentence, but for some reason my for-loop keeps iterating by 2 (figured this out by printing out the value of i during each iteration). What's wrong with it?
//input
Scanner input = new Scanner(System.in);
String sentence;
//prompt
System.out.print("Type a sentence. \nThe number of vowels will be counted.");
sentence = input.nextLine();
//vowel check
int charcount = 0;
String temp;
for(int i = 0; i < sentence.length(); i++)
{
temp = sentence.substring(i, i++);
if (temp.equalsIgnoreCase("a") == true)
charcount ++;
else if (temp.equalsIgnoreCase("e") == true)
charcount ++;
else if (temp.equalsIgnoreCase("i") == true)
charcount ++;
else if (temp.equalsIgnoreCase("o") == true)
charcount ++;
else if (temp.equalsIgnoreCase("u") == true)
charcount ++;
}
System.out.print("There are " + charcount + " vowels in your sentence.");
}
}
i, i++
??? That's going to have an effecttemp = sentence.substring(i, i+1); to this.
substring()
withcharAt(i)
it returns the character (as achar
) and is clearer as to the intent.for (char temp: sentence.toCharArray()) if ("AEIOUaeiou".indexOf(temp) != -1) charcount++;
is another way of doing this.