java cannot find symbol: method toLowerCase(String)

Viewed 709

I was trying to write a method named isVowel that returns whether a String is a vowel (a single-letter string containing a, e, i, o, or u, case-insensitively). Meanwhile, find there's a confliction in character and string. Now, what to do? Thank you all.

public static boolean isVowel(String c)
{
    String c = Character.toLowerCase(c);
    return c=="a"||c=="e"||c=="i"||c=="o"||c=="u";

}

variable c is already defined in method isVowel(String) !!no suitable method found for toLowerCase(String)

2 Answers

You are passing String where Character is expected. If you are passing only single character in String then use below to convert to lowercase.

public static boolean isVowel(String s)
{
    char c = Character.toLowerCase(s.charAt(0));
    return c=='a'||c=='e'||c=='i'||c=='o'||c=='u';
}
  1. You declare an identifier c twice in the same method scope, as a parameter, and as a local variable, which will not compile;
  2. Use char as a type of your parameter, instead of String, otherwise you risk to accept the string that is longer than 1 character; besides, String object is much heavier;
  3. Generally, [almost] never compare strings with == operator. Use .equals(Object object), instead.

Better, cleaner and faster method design would be this:

public static boolean isVowel(char c) {
    return "aeiouAEIOU".contains(String.valueOf(c));
}

or even better:

public static boolean isVowel(char c) {
    return "aeiouAEIOU".indexOf(c)!=-1;
}

indexOf(int char) returns -1, if char is not found.

Related