Simple number application
I'm doing the online Stanford "Programming Methodology" (which is great so far btw). One of the assignments is this:
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, as illustrated in this sample run:
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.
(from http://see.stanford.edu/materials/ic...imple-java.pdf)
I have this code, which works, but it feels like it could be simpler. How does it look? Also, I have
" high += ((high - SENTINEL) + low); "
because
" int high = low; "
gives me an error of a duplicate variable high, even though both lines give the same value. Is there a better way of doing this? Also, SENTINEL should be a constant but I'm not sure how I do that.
" private static final int SENTINEL = 0; "
gives an error.
here is the code that I have..
Quote:
import acm.program.*;
public class FindRange extends ConsoleProgram {
public void run() {
int SENTINEL = 0;
int high = 0;
int low = 0;
while (true) {
int userInput = readInt("? ");
if (userInput > high) {
high += (userInput - high);
}
if (userInput < low) {
low += (userInput - low);
}
if (userInput == SENTINEL) {
if (high == SENTINEL && low == SENTINEL) {
println("First entry was the sentinel.");
break;
}
if (high == SENTINEL) {
high += ((high - SENTINEL) + low);
}
if (low == SENTINEL) {
low += ((low-SENTINEL) + high);
}
println("smallest: " + low);
println("largest: " + high);
break;
}
}
}
}