开发者

Whitespace detector returning errors

开发者 https://www.devze.com 2023-04-10 05:02 出处:网络
I created a method to basically detect white space characters.I go through a string and check each character for white space. If it is a white space character, I return true, and if it\'s not, I retur

I created a method to basically detect white space characters. I go through a string and check each character for white space. If it is a white space character, I return true, and if it's not, I return false. However, I get a compilation error, stating "mis开发者_StackOverflow社区sing return statement". As I already have two return statements "true" and "false", I can't see why there is an error. Can you help me out or point me in the right direction? Thanks in advance.

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


Imagine if string.length() were 0. What would get returned?

Also, note that this doesn't do what you stated, which is to go through a string and check each character. It actually isn't checking anything about the string at all because of your use of i. If it were checking the string, it still would only check the first character of the string. If that character is whitespace, true is immediately returned, and if not, false is immediately returned.


You are looping over the length of the String, yet trying to return inside that loop. The logic doesn't make sense.

Think about the problem you are trying to solve - do you want to test if a character is a whitespace, or if an entire String contains at least one whitespace character? For the latter:

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

return hasWhite;

EDIT: A much simpler approach, if you're into that sorta thing ;-) -

return string.contains(" ");


Here is what your code should look like:

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
}

Note that this caters for the edge cases of a blank (zero-length) string and a null string

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号