DeanTwit
DeanTwit

Reputation: 335

Check if the input number is in a valid binary format

i tried to make a simple program,which check if the input number from the user is a binary number and that number is in correct binary format -> without leading zeros. That below is my code,but it doesn't work. I would appreciate if someone could help.

    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");
    }
}

Upvotes: 4

Views: 8391

Answers (6)

garagol
garagol

Reputation: 15

   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");
    }
}

Upvotes: 0

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59988

There are a better solution, you can check if your input contain only 0 and 1 and the input great then 0 then valide number, so instead you can use String for example :

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]+") will check if your input contain only 0 and 1.

  2. !num.startsWith("0") this to answer this part without leading zeros


Test:

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

Upvotes: 3

developer_hatch
developer_hatch

Reputation: 16224

I think you need to check your "if" condition before the while, because you don't want that the number starts with 0, right? so... just ask for it, I have tryied and worded fine to me:

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);
        }
    }

}

The rest of your code Fulfills its mission! It tells you if the number is binary or not, and now plus tells you if your code begins with useless zeros

Upvotes: 0

Yahya
Yahya

Reputation: 14072

You can try something like this:

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");
    }
}

Test:

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!

Upvotes: 1

W.Gray
W.Gray

Reputation: 119

you should not use sl.nextInt(); it will transfer '011' to 11, so when user input '011', the variable 'num' get the int value 11. You should simply use sl.next() to get the input of user.

Upvotes: 0

Sogomn
Sogomn

Reputation: 314

Why not simply use the standard library methods?

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

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

Upvotes: 0

Related Questions