Emmanuel Amzallag
Emmanuel Amzallag

Reputation: 3

How to create boolean method using return true statement

I need to make a boolean method that takes in a string and checks if it is a binary number. If it is binary it should return true, if it contains anything other than 0s and 1s, return false. Here is my code:

public static boolean CheckInputCorrect(String input) {
    int len = input.length();
    for(int i=0; i<len; i++)

        if(input.charAt(i) == '1' || input.charAt(i) == '0') {
            continue;
            return true;
        } else {
            break; 
            return false;
      }
 }

I suspect a syntax error, however no matter what I try it finds an error. Any help would be greatly appreciated!

Upvotes: 0

Views: 10011

Answers (2)

Ted Hopp
Ted Hopp

Reputation: 234847

Check each character and if it is not 0 or 1, then return false immediately. If you get through all the characters, return true:

public static boolean CheckInputCorrect(String input) {
    final int len = input.length();
    for (int i = 0; i < len; i++) {
        final char c = input.charAt(i);
        if (c != '1' && c != '0') {
            return false;
        }
    }
    return true;
}

There's no need for continue or break statements. Certainly don't use continue or break just before another statement; that usually generates a "not reachable" compiler error.

Note that you could also do this test by using a regular expression:

public static boolean CheckInputCorrect(String input) {
    return input.matches("[01]*");
}

and if this is going to be called multiple times, it would be more efficient to compile the pattern:

private static Pattern zerosOrOnes = Pattern.compile("[01]*");

public static boolean CheckInputCorrect(String input) {
    return zerosOrOnes.matcher(input).matches();
}

Upvotes: 4

rgettman
rgettman

Reputation: 178293

If the current character is a 1 or a 0, then you can't make a decision yet; it's just good so far.

If it's not 1 and it's not 0, then you can immediately return false. Once you have run through the entire String, then you can return true after the for loop ends.

for(int i=0; i<len; i++)
{
    if(! (input.charAt(i) == '1' || input.charAt(i) == '0'))
    {
       return false;
    }
}
return true;

Upvotes: 3

Related Questions