import java.util.*; import java.io.*; /* ====================================================================== */ /** This class converts decimals and binary * */ class BinaryToDecimal { public static void main( String [] args ){ getBinaryNumberFromUser(); //asks the user to type a binary number int Sum=0; int Exponent=0; while( notDone() ){ int binary_digit = getNextDigit(); //moves right to left int getNextDigit; int digit=binary_digit; int decimal_number= digit * (int)Math.pow(2, Exponent); Sum= Sum + (int) decimal_number; Exponent++; System.out.println("sum =" + Sum); } } //end main /* ===================================================================== */ /** This method is used to read in a single binary number. In order for * it to work properly, the user must enter 1s and 0s. * */ public static BinaryNumber getBinaryNumberFromUser(){ try{ System.out.println("Type in a binary number:"); BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); String message = input.readLine(); input.close(); binary_number = new BinaryNumber(message); }catch(IOException e){System.out.println("Unable to read a number");} //this only happens if there was an exception return new BinaryNumber(""); } //method: read public static boolean notDone(){ return binary_number.notDone(); } public static int getNextDigit(){ return binary_number.getNextNum(); } private static BinaryNumber binary_number; private static class BinaryNumber{ private String number; private int index; public BinaryNumber(String number){ this.number = number; index = number.length(); } public int getNextNum(){ int n = Integer.parseInt(number.substring(index-1,index)); index--; return n; } public boolean notDone(){ return (index > 0); } } } //class: BinaryToDecimal