I wrote this program, it accepts values from the user until the sentinel value of 0 is reached, it then prints the highest and lowest numbers entered. (it is meant to print a message if no values were entered)
import acm.program.*; public class FindRange extends ConsoleProgram { private static final int SENTINEL = 0; public void run() { println("This program finds the largest and smallest numbers."); int largest; int smallest; int value = readInt("?"); if (value == SENTINEL) { println("No values were entered"); } else { smallest = value; largest = value; while (value!=SENTINEL) { if (value < smallest) { smallest = value; } else if (value > largest) { largest = value; } value = readInt("?"); } println("smallest: " + smallest); println("largest: " + largest); } } }
that program works fine, but in the next lecture, this idea of a loop and a half was introduced where a program of the form
read value while (value != sentinel) process value read value
can be rewritten as
while (true) read value if (value == sentinel) break; process value
to avoid code duplication. to me it looks like this question was designed to be solved using the loop and a half method, but i cant seem to crack it. i tried this code
import acm.program.*; public class FindRange extends ConsoleProgram { private static final int SENTINEL = 0; public void run() { println("This program finds the largest and smallest numbers."); int smallest = 0; int largest = 0; int value = 0; while (true) { value = readInt("?"); if (value == SENTINEL) { println("smallest: " + smallest); println("largest: " + largest); break; } if (value > largest) { largest = value; } else if (value < smallest) { smallest = value; } } } }
but its has a major flaw in that the smallest value must be < 0 and the greatest value must be < 0. and i cant really see an easy way to solve this problem. (all i can think of is that the first value entered must be stored as both the smallest and largest value, but this must occur outside of the while loop, which just brings about a mess. or i could use a counter, but thats another variable, again a mess.)
to me the idea of the loop and a half thing is to simplify code, but it looks like i will have to make the code more complex in order to implement the loop and a half.
firstly, is it possible to simplify my original program using the loop and a half technique?
secondly, can anyone help me? some hints perhaps?