Java找不到符号:方法 toLowerCase(String)

huangapple go评论71阅读模式
英文:

java cannot find symbol: method toLowerCase(String)

问题

我正在尝试编写一个名为isVowel的方法,该方法将返回一个布尔值,指示一个字符串是否为元音字母(即包含字符a、e、i、o、u中的任意一个,不区分大小写)。与此同时,发现在字符和字符串之间存在冲突。现在应该怎么办?谢谢大家。

public static boolean isVowel(String c)
{
    char ch = Character.toLowerCase(c.charAt(0));
    return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
}

变量c在方法isVowel(String)中已经被定义过了。
未找到合适的方法可以将String转换为小写。

英文:

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)

答案1

得分: 2

你正在传递String,但需要Character
如果你只传递了单个字符在String中,使用以下代码将其转换为小写。

public static boolean isVowel(String s)
{
    char c = Character.toLowerCase(s.charAt(0));
    return c=='a'||c=='e'||c=='i'||c=='o'||c=='u';
}
英文:

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';
}

答案2

得分: 1

  1. 在同一个方法作用域中两次声明标识符 c,一次作为参数,一次作为局部变量,这将无法编译;
  2. 将参数的类型使用 char,而不是 String,否则您可能会接受长度超过1个字符的字符串;此外,String 对象更加庞大;
  3. 通常几乎不要使用 == 操作符来比较字符串。而应该使用 .equals(Object object) 方法。

更好、更清晰、更快的方法设计如下:

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

甚至可以更好地优化:

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

indexOf(int char) 返回 -1,如果未找到字符。

英文:
  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.

huangapple
  • 本文由 发表于 2020年10月27日 00:08:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/64540854.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定