简体   繁体   English

如何在 Java 中检查字符串是否为二进制

[英]How to check if a string is binary in Java

   /**
     * Given a String as input, return true if the String represents a valid
     * binary value (i.e. contains only the digits 1 and 0). Returns false if
     * the String does not represent a binary value.
     *
     * @param value
     *            A String value that may contain a binary value
     * @return true if the String value contains a binary value, false otherwise
     */

No matter what I do it only returns false.无论我做什么,它只会返回 false。 I am new to programming and suck at seeing how the logic runs.我是编程新手,不知道逻辑是如何运行的。 Thank you for any and all help.感谢您的任何帮助。

public static boolean validBinary(String value) {

    int b = Integer.parseInt(value);
    int binCount = 0;
    for(int i = 0; i < value.length(); i++) {
        int tempB = value.charAt(i);
        if(tempB % 10 == 0 || tempB % 10 == 1) {
            binCount = binCount + 1;
        }
        else {
            binCount = -1;
            break;
        }
    }
    if (binCount > 0) {
        return true;
    }
    else {
        return false;
    }

}

I believe your issue is here: int tempB = value.charAt(i);我相信你的问题在这里: int tempB = value.charAt(i); You convert tempB into a char, which is being cast to an int.您将 tempB 转换为 char,然后将其转换为 int。 But that converts it to its ASCII int value, so each '0' char is cast to 48 and each '1' value is cast to 49. Note: neither 48 nor 49 is zero or one mod 10, so nothing is ever being added to bin.但这会将其转换为它的 ASCII int 值,因此每个“0”字符被转换为 48,每个“1”值被转换为 49。注意:48 和 49 都不是零或一个 mod 10,所以没有添加任何内容到斌。

You need to convert each char to its actual integer value (namely, zero or one), with String.valueOf or Character.getNumericValue:您需要使用 String.valueOf 或 Character.getNumericValue 将每个字符转换为其实际的整数值(即零或一):

https://www.javatpoint.com/java-char-to-int https://www.javatpoint.com/java-char-to-int

Otherwise (besides the fact that you never use the b variable anywhere, so don't really need it) your logic looks pretty sound.否则(除了您从未在任何地方使用 b 变量的事实,所以并不真正需要它)您的逻辑看起来很合理。

Here is step by step analysis of your program.这是对您的程序的逐步分析。

public static boolean validBinary(String value) {

Get rid of the following as it is not used.删除以下内容,因为它没有被使用。

    int b = Integer.parseInt(value);

Initializing binCount and starting the loop.初始化binCount并开始循环。

    int binCount = 0;
    for(int i = 0; i < value.length(); i++) {
        int tempB = value.charAt(i);

This is where the problem starts.这就是问题开始的地方。 Even though tempB is declared an int it still has the value of an ASCII character.即使tempB被声明为int它仍然具有 ASCII 字符的值。 So '0' thru '9' are really 48 thru 57 inclusive.因此,“0”到“9”实际上是 48 到 57(包括 48 到 57)。 So instead of converting to integers, just compare them as they exist which are characters.因此,与其转换为整数,不如将它们作为字符进行比较。 In that case you can forget the % operator.在这种情况下,您可以忘记 % 运算符。 So the new if statement should be:所以新的 if 语句应该是:

    if (tempB == '0' || tempB == '1') {

instead of代替

    if(tempB % 10 == 0 || tempB % 10 == 1) {

Keep the rest of your code and the program should work just fine.保留其余代码,程序应该可以正常工作。

      binCount = binCount + 1;
    }
    else {
            binCount = -1;
            break;
        }
    }
    if (binCount > 0) {
        return true;
    }
    else {
        return false;
    }
}

Possible Improvements可能的改进

The whole point of the exercise is to validate whether the number is binary.练习的重点是验证数字是否为二进制。 So you don't need any bookkeeping such as bincount do do that.所以你不需要任何簿记,比如bincount就可以做到这一点。 As soon as your test for 0 or 1 fails, just return false .一旦您对01测试失败,就返回false No need for further processing.无需进一步处理。 But if you finish checking the entire string and haven't failed the test, then all the characters must be 0 or 1. So return true .但是如果你完成了整个字符串的检查并且没有通过测试,那么所有的字符都必须是 0 或 1。所以返回true That would look like this.那看起来像这样。

  for(int i = 0; i < value.length(); i++) {
        int tempB = value.charAt(i);
        if (tempB == '0' || tempB == '1') {
             continue; // process next character.
                       // continue skips rest of loop
         }
         return false;
   }
   // no failures, so
   return true;

Alternative logic without the continue could be:没有continue替代逻辑可能是:

  for(int i = 0; i < value.length(); i++) {
        int tempB = value.charAt(i);
        if (tempB != '0' && tempB != '1') {
             return false;
         }
   }
   // no failures, so
   return true;

You could use a basic regular expression:您可以使用基本的正则表达式:

public static final String BIT_REGEX = "[01]{1,}";
Pattern pattern = Pattern.compile(BIT_REGEX);
Matcher matcher = pattern.matcher(value);
isValid = matcher.matches();

public static boolean validBinary(String value) {公共静态布尔有效二进制(字符串值){

int binCount = 0;
int len = value.length();
for(int i = 0; i < len; i++) {
    char tempB = value.charAt(i);
    if(tempB == '0' || tempB == '1') {
        binCount = binCount + 1;
        continue;
    }
    else {
        binCount = -1;
        break;
    }
}
if (binCount > 0) {
    return true;
}
else {
    return false;
}

} }

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

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