cs106a – Assignment #2 – Task #5

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:

cs106a – assignment #2 – task #5

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.

Start by printing the program description. Read the fist value, if it is equal to the sentinel print an adequate message, otherwise set two helper variables representing the current smallest and largest numbers equal to the first value. Inside the following infinite loop, read the next number and stop processing if it is equal to the sentinel. Adjust the two helper variables if necessary. And finally print the result:

	public void run() {
		println("This program finds the largest and smallest numbers.");

		int value = readInt("? ");

		if (value == SENTINEL_VALUE) {
			println("No values have been entered.");
		} else {
			int smallest = value;
			int largest = value;
			while (true) {
				value = readInt("? ");
				if (value == SENTINEL_VALUE) break;
				if (smallest > value) smallest = value;
				else if (largest < value) largest = value;
			}
			println("smallest: " + smallest);
			println("largest: " + largest);
		}	
	}

The code for this assignment is available on github.

Facebooktwittergoogle_plusredditpinterestlinkedintumblrmailFacebooktwittergoogle_plusredditpinterestlinkedintumblrmail

Flattr this!

Leave a Reply

Your email address will not be published. Required fields are marked *