检查输入的数字是否采用有效的二进制格式

时间:2017-05-15 13:23:42

标签: java binary

我尝试制作一个简单的程序,检查用户的输入数字是否为二进制数,且该数字是否为正确的二进制格式 - >没有前导零。以下是我的代码,但它不起作用。如果有人可以提供帮助,我将不胜感激。

    public class CheckNumberBinary {
    public static void main(String args[]) {
        int r = 0, c = 0, num, b;

        Scanner sl = new Scanner(System.in);
        num = sl.nextInt();
       int firstDigit = Integer.parseInt(Integer.toString(num).substring(0, 1));// i want to get the first digit from the input
        if (firstDigit>0||firstDigit==1 ){
            while (num > 0) {
                if ((num % 10 == 0) || (num % 10 == 1))
                    c++;
                r++;
                num = num / 10;
            }
            if (c == r) {
                System.out.println(true);
            } else
                System.out.println(false);
        } else System.out.printf("WARNING: The number starts with 0");
    }
}

6 个答案:

答案 0 :(得分:2)

有一个更好的解决方案,你可以检查你的输入是否只包含0和1,输入大于0然后是valide数,所以你可以使用String例如:

String num;
Scanner sl = new Scanner(System.in);
num = sl.next();
if (num.matches("[01]+") && !num.startsWith("0")) {
    System.out.println("Correct number :" + num);
}else{
    System.out.println("Not Correct number!");
}
  1. num.matches("[01]+")将检查您的输入是否仅包含0和1.

  2. !num.startsWith("0")这回答了这部分没有前导零

  3. <强>测试

    10010     -> Correct number :10010
    00001     -> Not Correct number!
    11101     -> Correct number :01101
    98888     -> Not Correct number!
    

答案 1 :(得分:0)

为什么不简单地使用标准库方法?

static boolean isValidBinary(final int input) {
    final String binary = String.valueOf(input);

    return binary.replaceAll("[01]", "").isEmpty() && !binary.startsWith("0");
}

答案 2 :(得分:0)

你不应该使用sl.nextInt();将'011'转移到11,所以当用户输入'011'时,变量'num'得到int值11。 您只需使用sl.next()来获取用户的输入。

答案 3 :(得分:0)

您可以尝试这样的事情:

public static void main(String args[]) {
     boolean binary=true;  // boolean for final decision
     String input; 
     int counter=0; // to count how many leading zeros there are in the input
     int target = 5; // specify how many leading zeros allowed!!

     Scanner in = new Scanner(System.in);
     input = in.nextLine(); // take the entire line as a String

    //first loop through the whole input to check for any illegal entry (i.e. non digits)
    for(char digit : input.toCharArray()){
         if(!Character.isDigit(digit)){ // catch any non-digit !
            System.out.println("Illegal Input Found!"); // inform user and exit
            System.exit(0);
         }
         if(digit!='0' && digit!='1'){ // check if it's not 1 and not 0
               binary = false;
         }
    }

    // now if there are no illegal inputs, check if it starts with leading zeros 
    if(input.charAt(0)=='0'){ // potential leading zeros, check the rest
       while(input.charAt(counter)=='0'){ // while there are followed zeros
            counter++;
            if(counter>target && binary){ // leading zeros only in case it's a binary
                System.out.println("Illegal Leading Zeros!");
                System.exit(0);
            }
        }
     }


    // now if your program reach this point that means the input is valid and doesn't contain leading zeros in case it's a binary
    if(binary){
       System.out.println("It is a binary number");
    }
    else{
         System.out.println("It is NOT a binary number");
    }
}

<强>测试

01010101  ->  It is a binary number
01010105  ->  It is NOT a binary number
0000001   ->  Illegal Leading Zeros!
0000005   ->  It is NOT a binary number
000000A   ->  Illegal Input Found!

答案 4 :(得分:0)

我认为您需要在之前检查“if”条件,因为您不希望该数字以0开头,对吗?所以...只是要求它,我已经尝试并措辞好对我:

public class CheckNumberBinary {
    public static void main(String args[]) {
        int r = 0, c = 0, num, b;

        Scanner sl = new Scanner(System.in);
        String input = sl.next();
        num = Integer.parseInt(input);
        String firstDigit = (input.length() > 0 ? input.substring(0, 1) : "" );
        if (firstDigit.equals("0")) {
            System.out.printf("WARNING: The number starts with 0");
        } else {

            while (num > 0) {
                if ((num % 10 == 0) || (num % 10 == 1))
                    c++;
                r++;
                num = num / 10;
            }
            if (c == r) {
                System.out.println(true);
            } else
                System.out.println(false);
        }
    }

}

您的其余代码履行其使命!它会告诉您数字是否为二进制,现在加号告诉您代码是否以无用的零开头

答案 5 :(得分:0)

   import java.util.*;

   public class BinaryTest {
    public static void main(String [] args){
        Scanner input=new Scanner(System.in);

        int count=0;
        boolean check=true;

        System.out.print("Enter a number: ");
        int num=input.nextInt();

        for(int i=0; i<=num; i++){
            count=num%10;
            if(count>1) {
                check=false;
            break;
            }
            else {
                check=true;
            }

            num=num/10;
        }
        if(check)
            System.out.println("Binary");
        else
            System.out.println("Not Binary");
    }
}