Check if the input number is in a valid binary format

Viewed 7481

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