First things first, you either need to reset r back to zero either before the while loop or after.
Next simplifying the code. If you're wanting to know how many vowels are in a String, you can use String.replaceAll(String regex, String replacement) to remove all non-vowel letters from the String then the length of the String will equal how many vowels you have.
public static void main(String[] args) {
String a = "banana";
System.out.println(a.replaceAll("[^aeiouAEIOU]", "").length());
}
Result:
3
The regex pattern, in the replaceAll(), means to match any character that is not a lower/upper case vowel (Regex Pattern Reference) and replace it with and empty string (remove it). The result is a new String with nothing but vowels in it.
If regex is too complicating to understand, then walk the String like you're already doing, but check if each character is a vowel like this:
public static void main(String[] args) {
String vowels = "aeiouAEIOU";
String a = "banana";
int vowelCount = 0;
for (int i = 0; i < a.length(); i++) {
String letter = Character.toString(a.charAt(i));
if (vowels.contains(letter)) {
vowelCount++;
}
}
System.out.println(vowelCount);
}
You don't need to use String.substring() to extract a single character, that's what String.charAt() is for. Also, instead of having an array of vowels, have a String of vowels so you can use String.contains() to see if the letter is a vowel.
As you can see, there are many ways to construct an algorithm to solve this problem. Choose what makes best sense to you and helps you learn.
ris never reset for one thingr = 0;before thewhileloop. In fact, you'd probably be better using an enhancedfor-looprwill be equal toe.length...therefore it will never enter thewhile-loopagain