【问题标题】:Whitespace detector returning errors空白检测器返回错误
【发布时间】:2011-11-29 05:57:52
【问题描述】:

我创建了一种基本检测空白字符的方法。我遍历一个字符串并检查每个字符是否有空格。如果是空格字符,我返回真,如果不是,我返回假。但是,我收到一个编译错误,指出“缺少返回语句”。由于我已经有两个返回语句“true”和“false”,我看不出为什么会出现错误。你能帮助我或指出我正确的方向吗?提前致谢。

public boolean isWhitespace()
{
    for (int i=0; i<string.length(); i++)
    {
        if (Character.isWhitespace(i))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

【问题讨论】:

  • 这是作业吗?感觉就像做家务。如果是这样,添加一个“家庭作业”标签。

标签: java string methods boolean


【解决方案1】:

想象一下,如果string.length() 为 0。会返回什么?

另外,请注意,这并没有按照您所说的进行,即遍历一个字符串并检查每个字符。由于您使用了i,它实际上根本没有检查任何关于字符串的内容。如果它正在检查字符串,它仍然只会检查字符串的第一个字符。如果该字符是空格,则立即返回 true,如果不是,则立即返回 false。

【讨论】:

    【解决方案2】:

    您正在循环字符串的长度,但试图在该循环内返回。逻辑没有意义。

    想想你要解决的问题——你想测试一个字符是否是空格,或者整个字符串是否包含至少一个空格字符?对于后者:

    boolean hasWhite = false;
    for(int i=0; i < string.length(); i++)
    {
      if(Character.isWhitespace(string.charAt(i)))
      {
         hasWhite = true;
         break;
      }
    }
    
    return hasWhite;
    

    编辑:一个更简单的方法,如果你喜欢那种东西;-) -

    return string.contains(" ");
    

    【讨论】:

    【解决方案3】:

    这是您的代码应该的样子:

    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
    }
    

    请注意,这适用于空白(零长度)字符串和空字符串的边缘情况

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-06
      • 1970-01-01
      • 2014-04-16
      • 2016-05-19
      • 2018-12-23
      • 2019-03-14
      相关资源
      最近更新 更多