waltermilner

Untitled

May 15th, 2016
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.84 KB | None | 0 0
  1. class Test {
  2.  
  3.   public static void main(String args[]) {
  4.     Scanner scanner = new Scanner(System.in);
  5.     System.out.println("Enter binary number");
  6.     String input = scanner.next();
  7.     // validate : 0 or 1 only
  8.     for (int pos = 0; pos < input.length(); pos++) {
  9.       char c = input.charAt(pos);
  10.       if (c != '0' && c != '1') {
  11.         System.out.println("Not binary");
  12.         System.exit(1);
  13.       }
  14.     }
  15.     System.out.println("Input valid");
  16.     int result = 0;
  17.     int factor = 1; // place value
  18.     int length = input.length();
  19.     // go through input, starting at the right
  20.     for (int pos = length - 1; pos > -1; pos--) {
  21.       char c = input.charAt(pos);
  22.       if (c == '1') {
  23.         result += factor;
  24.       }
  25.       factor *= 2; //  next place value
  26.     }
  27.     System.out.println("In decimal " + result);
  28.   }
  29. }
Advertisement
Add Comment
Please, Sign In to add comment