The problem is “Determining the Range, 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.
”
So once again broken down the problem into parts, first part need to read in the values from the keyboard and the next part is to set the lowest and the highest values (whilst making sure that no value takes the sentinel value).
Here is a example of the output from the running program
This program finds the smallest and largest integers in a list. Enter values, one per line, using a 0 to signal the end of the list
?32
?2
?4
?5
?45
?1
?0
Smallest value was 1
Largest value was 45
source code in full, I have included within zip file and also the PDF file of the full assignment problems.
/*
* 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.*;
import java.io.Console;
public class FindRange extends ConsoleProgram {
public void run() {
int readInValue=sential;
println("This program finds the smallest and largest integers in a list. Enter values, one per line, using a "+sential+" to signal the end of the list");
do
{
readInValue = readInt("?");
if (readInValue != sential)
{
if (readInValue > largestValue)
largestValue = readInValue;
if (readInValue < smallestValue || smallestValue == sential)
smallestValue = readInValue;
}
} while (readInValue != sential);
if (largestValue == smallestValue && largestValue == sential)
{
println("No values inputted");
}
else
{
println("Smallest value was "+ smallestValue);
println("Largest value was " + largestValue);
}
}
private int largestValue = 0, smallestValue = 0;
private static final int sential = 0;
}
The sentinel should not be included in calculating the largest or smallest, it simply marks the end of the list.
However, if all the integers are negative, the program states that the largest integer is 0, which is wrong.
//note: this program works for ALL cases except for if the user ONLY enters 2147483647 and -2147483648. it will work if they enter one of them (alone or with other integers).