import java.util.Scanner; class Atoi_Elegant { /* --- parseInt(s): Ascii to Integer conversion function --- */ public static int myParseInt(String s) { int value, sign; int pos; /* ------- Check for negative sign ------- */ if (s.charAt(0) == '-') { sign = -1; pos = 1; // Start at digit s.charAt(1) } else { sign = 1; pos = 0; // Start at digit s.charAt(0) } /* ------------------------------------------ Compute the absolute value of the number ------------------------------------------ */ value = 0; for (int k = pos; k < s.length(); k++) { value = 10*value + ( s.charAt(k) - 48 ); // High school knowledge.... } /* ------------------------------------------------- Adjust sign if necessary (sign = 1 or -1 !!!) ------------------------------------------------- */ return(sign*value); // Return a BINARY 2's compl code } public static void main(String[] args) { Scanner in = new Scanner(System.in); String s1, s2; int i1, i2; System.out.print("Enter an integer (string) s1: "); s1 = in.next(); System.out.println("We read the numeric string: \"" + s1 + "\""); i1 = myParseInt(s1); // Same effect as: i1 = Integer.parseInt(s1); !!!! System.out.println("The integer VALUE for this numeric string is: " + i1); System.out.print("\nEnter another integer (string) s2: "); s2 = in.next(); System.out.println("We read the numeric string: \"" + s2 + "\""); i2 = myParseInt(s2); // Same effect as: i1 = Integer.parseInt(s1); !!!! System.out.println("The integer VALUE for this numeric string is: " + i2); System.out.println("==================================================="); System.out.println("The sum of the integer values = " + (i1+i2) ); } }