Java 返回错误的空白检测器
我创建了一个基本上检测空白字符的方法。我遍历一个字符串,检查每个字符是否有空格。如果是空白字符,则返回true;如果不是,则返回false。然而,我得到一个编译错误,声明“缺少返回语句”。由于我已经有两个返回语句“true”和“false”,我不明白为什么会有错误。你能帮我吗,或者给我指出正确的方向?提前谢谢Java 返回错误的空白检测器,java,string,methods,boolean,Java,String,Methods,Boolean,我创建了一个基本上检测空白字符的方法。我遍历一个字符串,检查每个字符是否有空格。如果是空白字符,则返回true;如果不是,则返回false。然而,我得到一个编译错误,声明“缺少返回语句”。由于我已经有两个返回语句“true”和“false”,我不明白为什么会有错误。你能帮我吗,或者给我指出正确的方向?提前谢谢 public boolean isWhitespace() { for (int i=0; i<string.length(); i++) { if
public boolean isWhitespace()
{
for (int i=0; i<string.length(); i++)
{
if (Character.isWhitespace(i))
{
return true;
}
else
{
return false;
}
}
}
public boolean isWhitespace()
{
对于(int i=0;i想象一下,如果string.length()
为0,将返回什么
另外,请注意,这与您所说的不同,即检查字符串并检查每个字符。由于您使用了i
,它实际上根本没有检查字符串的任何内容。如果它检查字符串,它仍然只检查字符串的第一个字符。如果该字符是空白,则true为immedi返回,如果不返回,则立即返回false。您在字符串长度上循环,但试图在该循环内返回。逻辑没有意义
考虑一下您试图解决的问题—是否要测试某个字符是空白字符,或者整个字符串是否至少包含一个空白字符?对于后者:
boolean hasWhite = false;
for(int i=0; i < string.length(); i++)
{
if(Character.isWhitespace(string.charAt(i)))
{
hasWhite = true;
break;
}
}
return hasWhite;
以下是您的代码的外观:
public boolean isWhitespace(String string) { // NOTE: Passing in string
if (string == null) { // NOTE: Null checking
return true; // You may consider null to be not whitespace - up to you
}
for (int i=0; i < string.length(); i++) {
if (!Character.isWhitespace(string.charAt(i))) { // NOTE: Checking char number i
return false; // NOTE: Return false at the first non-whitespace char found
}
}
return true; // NOTE: Final "default" return when no non-whitespace found
}
public boolean isWhitespace(字符串){//注意:传入字符串
if(string==null){//注意:null检查
返回true;//您可以考虑NULL不是空白
}
对于(int i=0;i
请注意,这符合空白(零长度)字符串和空字符串的边缘情况这是家庭作业吗?感觉像是家庭作业。如果是这样,请添加一个“家庭作业”标记。或更短的标记:return string.contains(“”);非常正确……我成了猴子陷阱()的受害者。我也会添加这个…return string.contains(“”);
public boolean isWhitespace(String string) { // NOTE: Passing in string
if (string == null) { // NOTE: Null checking
return true; // You may consider null to be not whitespace - up to you
}
for (int i=0; i < string.length(); i++) {
if (!Character.isWhitespace(string.charAt(i))) { // NOTE: Checking char number i
return false; // NOTE: Return false at the first non-whitespace char found
}
}
return true; // NOTE: Final "default" return when no non-whitespace found
}