-2

I need to count the vowels but this is always returning 0?

public static int numVowel(String s) {
  int count = 0,x;
  for(x = 0; x<s.length();x++)
    if (x=='a' || x=='e' || x=='i' || x=='o' || x=='u' || x=='A' || x=='E' || x=='I' || x=='O' || x=='U')
    count++;
  return count;
}
GhostCat
  • 137,827
  • 25
  • 176
  • 248

4 Answers4

0

You are comparing your counter/index against char literals.

Instead, you should retrieve the character at the indexed position against these literals! See Get string character by index - Java here for how to do that!

GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

It should be s.charAt(x) == 'a' instead of x == 'a'. You should check the character at the given index.

shmosel
  • 49,289
  • 6
  • 73
  • 138
0

You don't want to check the value of x; you want to check the value of the character at position x. You can do this with s.charAt(x).

Adam P
  • 4,603
  • 6
  • 31
  • 40
0

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();
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249