Add2Integers - * @return The integer read */ private int...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
/* * 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
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: * @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"); } } }...
View Full Document

This note was uploaded on 10/27/2009 for the course COMP SCI 1MD3 taught by Professor Various during the Winter '07 term at McMaster University.

Ask a homework question - tutors are online