// // File: /home/cs255001/demo/atoi/Atoi_1.java // // This is a "gentle" introduction to the String => int conversion algorithm // This program convert a 2 digit number // import java.util.Scanner; import java.util.Arrays; public class ConvStr2Digits { public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); String s = null; int[] v = new int[2]; // Variable to save int values of the digits int x; while ( true ) { System.out.print("\nEnter input: "); s = in.next( ); // Read a String from key board if ( s.length() != 2 ) { System.out.println("Error: you must use a string of 2 digits !"); } System.out.println("\nASCII codes (in decimal) = " + (int) s.charAt(0) + " " + (int) s.charAt(1) ); /* ------------------------------------------------------- Convert the ASCII character to 2's compl - per digit ------------------------------------------------------- */ v[0] = s.charAt(0) - '0'; v[1] = s.charAt(1) - 48; // 48 = '0' !!! System.out.println(" v[0] = " + v[0] + "(=" + Integer.toBinaryString(v[0]) + "(bin))" + ", v[1] = " + v[1] + "(=" + Integer.toBinaryString(v[1]) + "(bin))" ); System.out.print(" Converting: " + Integer.toBinaryString(v[0]) + "(bin)*" + Integer.toBinaryString(10) + "(bin) + " + Integer.toBinaryString(v[1]) + "(bin)"); x = v[0]*10 + v[1]; // Computation will be performed in BINARY ! System.out.println(" = " + Integer.toBinaryString(x) + "(bin)" ); System.out.println("\nInteger value x = " + x ); /* ============================================================= Proof this is an integer that you can use in computation ============================================================= */ x = x + 1; System.out.println("\nPerforming a calculation with the output:"); System.out.println("After adding 1, x = " + x + "\n"); } } }