This is question #2 of Assignment #2 of Programming Methodology CS106a:
Write a ConsoleProgram that reads in a list of integers, one per line, until 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 smallest and largest values in the
list…
Your program should handle the following special cases:
• If the user enters only one value before the sentinel, the program should report
that value as both the largest and smallest.
• If the user enters the sentinel on the very first input line, then no values have been
entered, and your program should display a message to that effect.
Below is my answer. Any suggestions to improve it?
/*
* File: FindRange.java
* --------------------
* This program is a stub for the FindRange problem,
* which finds the smallest and
* largest values in a list of integers.
*/
import acm.program.*;
public class FindRange extends ConsoleProgram {
/* FindRange finds the smallest and the largest
* in a list of integers entered by the user
* and stops with a sentinel value of 0.
*
* */
private static final int SENTINEL = 0;
public void run() {
println("This program finds the largest and smallest numbers.");
int Firstnumber=readInt("?");
if (Firstnumber==SENTINEL){
println("No values have been entered.");
}
else{
int largestNumber= Firstnumber;
int smallestNumber= Firstnumber;
while (true) {
int number = readInt("?");
if (number == SENTINEL) break;
if (number != 0 && number<=smallestNumber){
smallestNumber = number;
}
if (number>=largestNumber){
largestNumber=number;
}
}
println("This program finds the largest and smallest numbers.");
println("Largest:" + largestNumber );
println("Smallest:" + smallestNumber );
}
}
}

Pingback: CS106A Assignment 2 - Find Range Solution | ...Zero to Hero