# Simple number application

• 05-31-2010, 02:07 AM
atomant
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) {

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;
}
}
}
}

• 05-31-2010, 02:37 AM
m00nchile
Since one of the assignment requirements are that the sentinel value should be easily changable, it's generally not a good idea to declare it as a constant, just for reference, setting a constant is done with the final modifyer:
Code:

`final int CONSTANT = 0;`
Next, you initialize your high and low variables with 0. What if the user enters -10 as the first number? The high variable won't get set, a better aproach would be this:
Code:

`int high = Integer.MIN_VALUE, low = Integer.MAX_VALUE;`
Since you based your logic on numbers entered on the sentinel value, you'd need to change a few things around.
Also, these lines don't really make sense:
Code:

```high += (userInput - high); low += (userInput - low);```
Just set the value, no need for the add and subtract magic.