// // File: /home/cs255001/demo/atoi/JavaInput_5.java // // Read in 1 character and convert char into int (2s compl) // // We use the **most general method (an IF statement)** by: // // Look up each symbol and map the digit to its assigned numeric value // import java.util.Scanner; public class ConvStr1DigitGen { public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); String s = null; int x = 0; while ( true ) { System.out.print("Enter input: "); s = in.next( ); // Read a String from key board if ( s.length() > 1 ) { System.out.println("Error: you must type 1 digit !"); System.out.println("Try again\n"); continue; } System.out.println("ASCII codes (in decimal) = " + (int) s.charAt(0) ); if ( s.charAt(0) == '0' ) x = 0; else if ( s.charAt(0) == '1' ) x = 1; else if ( s.charAt(0) == '2' ) x = 2; else if ( s.charAt(0) == '3' ) x = 3; else if ( s.charAt(0) == '4' ) x = 4; else if ( s.charAt(0) == '5' ) x = 5; else if ( s.charAt(0) == '6' ) x = 6; else if ( s.charAt(0) == '7' ) x = 7; else if ( s.charAt(0) == '8' ) x = 8; else if ( s.charAt(0) == '9' ) x = 9; else { System.out.println("Input '"+s.charAt(0)+"' is NOT a digit !\n"); continue; } System.out.println("integer 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\n"); } } }