英文:
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
- 在同一个方法作用域中两次声明标识符
c
,一次作为参数,一次作为局部变量,这将无法编译; - 将参数的类型使用
char
,而不是String
,否则您可能会接受长度超过1个字符的字符串;此外,String
对象更加庞大; - 通常几乎不要使用
==
操作符来比较字符串。而应该使用.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
,如果未找到字符。
英文:
- You declare an identifier
c
twice in the same method scope, as a parameter, and as a local variable, which will not compile; - Use
char
as a type of your parameter, instead ofString
, otherwise you risk to accept the string that is longer than 1 character; besides,String
object is much heavier; - 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论