/* * File: Add2Integers.java * ----------------------- * This program adds two integers and prints their sum. * This version defines its own implementation of readInt. * * Author: CS1MD3, Nov. 2008 */ import acm.program.*; public class Add2Integers extends ConsoleProgram { public void run() { println("This program adds two integers."); int n1 = myReadInt("Enter n1: "); int n2 = myReadInt("Enter n2: "); int total = n1 + n2; println("The total is " + total + "."); } /** * Simulates readInt method. * @param prompt The prompt string * @return The integer read */ private int myReadInt(String prompt) { while (true) { int value = 0; int sign = +1; String line = readLine(prompt); if (line.startsWith("-")) { sign = -1; line = line.substring(1); } int n = line.length(); boolean okay = (n > 0); for (int i = 0; okay && i < n; i++) { char ch = line.charAt(i); if (Character.isDigit(ch)) { value = 10 * value + (ch - '0'); } else { okay = false; } } if (okay) return sign * value; println("Illegal integer format"); } } }