简体   繁体   English

如何使用return true语句创建布尔方法

[英]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. 如果是二进制,则应返回true;如果包含0和1,则返回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! 任何帮助将不胜感激!

Check each character and if it is not 0 or 1, then return false immediately. 检查每个字符,如果它不是 0或1,则立即返回false If you get through all the characters, return true : 如果您遍历所有字符,则返回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. 无需continuebreak语句。 Certainly don't use continue or break just before another statement; 当然,不要在另一个语句之前使用continuebreak 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();
}

If the current character is a 1 or a 0 , then you can't make a decision yet; 如果当前字符是10 ,那么您还不能做出决定; it's just good so far. 到目前为止,一切都很好。

If it's not 1 and it's not 0 , then you can immediately return false . 如果它不是1也不是0 ,则可以立即返回false Once you have run through the entire String , then you can return true after the for loop ends. 一旦遍历了整个String ,然后可以在for循环结束后返回true

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM