The Art and Science of Java, Chapter 4, Exercise 12 Solution
Write a ConsoleProqrarn that reads in a list of integers, one per line, until the user enters a sentinel value of 0 (which you should be able to change easily to some other value), When the sentinel is read , your program should display the largest value in the list, as illustrated in this sample run below:
This program finds the largest integer in a list . Enter values, one per line, using a 0 to signal the end of the list . ? 17 ? 42 ? 11 ? 19 ? 35 ? 0 The largest value is 42
Solution:
/* * FindLargest.java * ---------------- * This program reads in integers one per line until user * enters a 0 as sentinel and then displays the largest number. */
import acm.program.*;
public class FindLargest extends ConsoleProgram{ public void run(){ println("This program finds the largest integer in a list."); println("Enter values, one per line, using a 0 to signal the end of the list:"); int largest = 0; while(true){ int numbers = readInt(""); if(numbers==SENTINEL) break; if(numbers>largest) largest = numbers; } println("The largest number is: " + largest); } private static final int SENTINEL = 0; }










