Hassan Zia
Hassan Zia

Reputation: 330

I can't restrict my program to accept only binary numbers

I'm creating a program for my gui number converter. I want my program to ask user a binary string and if he does not enter a binary number, the program will show him error message and will ask him to enter again. The problem is that I can add restriction to alphabets but when it comes to numbers then it fails or it keeps showing the error message.

import java.util.*;

public class test {
    Scanner key = new Scanner(System.in);
    String in;
    int b;
    public test(){
        do{
            System.out.println("Enter the binary string of 5 numbers");
            in = key.nextLine();
            int i,j;
            char ch;
            for (i=0 ; i<=5 ; i++){
                b = 0;
                ch = in.charAt(i);
                j = ch;
                if (Character.isDigit(ch) && ch<=0 && ch>=1)
                    b = 1;
                else
                    System.out.println("Please enter a binary number (1 , 0)");
                break;
                //b = 1;
            }
        }while(b != 1);

        int c;
        c = Integer.parseInt(in);
        System.out.println("your number is: " + c );
    }

    public static void main (String args[]){
        test obj = new test();
    }
}

Upvotes: 1

Views: 1323

Answers (3)

Andrew
Andrew

Reputation: 5083

ch<=0 && ch>=1 does not do what you think it does. The character codes for "0" and "1" are 48 and 49, so you should check for those instead. Also, your >= comparators are backwards, but that's not really the clearest way to write this code. And since you're comparing for just those two values, Character.isDigit(ch) is redundant.

Try one of these:

ch == 48 || ch == 49

ch == '0' || ch == '1'

Upvotes: 7

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

1) First logic error here for (i=0 ; i<=5 ; i++) replace i<=5 to i<5

2) change the if else condition like below

if (Character.isDigit(ch) && (ch == '0' || ch == '1'))
{
     b = 1;
}
else
{
     System.out.println("Please enter a binary number (1 , 0)");
     break;
}

Upvotes: 0

Reimeus
Reimeus

Reputation: 159784

Scanner has an overloaded nextInt method that uses a radix

int binaryNumber = scanner.nextInt(2);

Upvotes: 2

Related Questions