Because x
is your index (not the characters from s
). Also, always use braces (even when they're optional). To fix it with your current approach, do something like
public static int numVowel(String s) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
char x = s.charAt(i);
if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O'
|| x == 'U') {
count++;
}
}
return count;
}
But I would prefer something like
public static int numVowel(String s) {
int count = 0;
for (char ch : s.toLowerCase().toCharArray()) {
if ("aeiou".indexOf(ch) > -1) {
count++;
}
}
return count;
}
Or use a regular expression to remove everything that isn't a vowel from the input String
and then return the length of that. Like,
public static int numVowel(String s) {
return s.toLowerCase().replaceAll("[^aeiou]", "").length();
}
If you need to invoke this many many times then the cost of calling String.toLowerCase()
is not insignificant; and you might compile that regex into a Pattern
.
private static Pattern _PATTERN = Pattern.compile("[^aeiouAEIOU]");
public static int numVowel(String s) {
return _PATTERN.matcher(s).replaceAll("").length();
}