public boolean isThereLetter(String name) {
char[] chars = name.toCharArray();
for (char c : chars) {
if(!Character.isLetter(c)) {
return false;
}
}
return true;
}
我这样调用了这个函数;
if(isThereLetter("Wdasdsa<>")){
Log.d(TAG, "there is a letter");
}else
Log.d(TAG,"there isn't any letter");
但我注意到因为“&lt;”这个char in ...(“Wdasdsa&lt;&gt;”)函数返回false。我该如何解决?
答案 0 :(得分:2)
你的条件倒退了。如果字符串中的所有字符都是字母,则当前实现返回true
。如果字符串中的任何字符是一个字母,那么听起来就像想要的返回true
。
public boolean isThereLetter(String name) {
char[] chars = name.toCharArray();
for (char c : chars) {
if(Character.isLetter(c)) {
return true;
}
}
return false;
}
答案 1 :(得分:2)
当你遇到至少一个角色时,立即返回true说该角色找到了。更改代码如图所示
public boolean isThereLetter(String name) {
char[] chars = name.toCharArray();
for (char c : chars) {
if(Character.isLetter(c)) {
//You came across atleat one character.
return true;
}
}
//Never reached into the if block. No any character found
return false;
}