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


i'm creating program gui number converter. want program ask user binary string , if not enter binary number, program show him error message , ask him enter again. problem can add restriction alphabets when comes numbers fails or keeps showing 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 binary string of 5 numbers");             in = key.nextline();             int i,j;             char ch;             (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 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();     } } 

ch<=0 && ch>=1 not think does. character codes "0" , "1" 48 , 49, should check instead. also, >= comparators backwards, that's not clearest way write code. , since you're comparing 2 values, character.isdigit(ch) redundant.

try 1 of these:

ch == 48 || ch == 49  ch == '0' || ch == '1' 

Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

android - Associate same looper with different threads -

visual studio 2010 - Connect to informix database windows form application -