Stanford CS106A Min / Max program

Posted on

Problem

I am learning Java through Stanford CS106A and I’m wondering how the code for this early assignment looks. I’ve worked in a proprietary scripting language before and so I’m trying to get the right programming form down for Java. It works but am I doing anything in the wrong way? Am I declaring and initializing my variables properly? Is using a counter and conditional for the first instance like this good form? Am I missing a shorter, more efficient way?

/*
 * File: FindRange.java
 */

import acm.program.*;

public class FindRange extends ConsoleProgram {

    /* Specifies the value of the sentinel */
    private static final int SENTINEL = 0;

    public void run() {
        println("This program finds the largest and smallest numbers entered.");
        println("Enter values, one per line, using " + SENTINEL + " to signal the end of the list.");
        int min = 0;
        int max = 0;
        int count = 0;
        while (true) {
            int value = readInt(" ? ");
            if (value == SENTINEL) break;
            count++;
            if (count == 1){
                min = value;
                max = value;
            }
            min = Math.min(min, value);
            max = Math.max(max, value);
        }
        if (count>0){
            println("Smallest: " + min);
            println("Largest: " + max);
        } else {
            println("No values were entered.");
        }
    }
}

Solution

You could initialize min with Integer.MAX_VALUE and max with Integer.MIN_VALUE, this would make the inner if obsolete. You could also use this for your output condition and get rid of the count completely.

Without knowing the complete assignment, it’s hard to optimize your code in any direction.

If you don’t want to use your library and do it in ‘plain’ Java have a look at Scanner.

Just a minor nitpick – you are using integer as a stopping condition, which means you are excluding a one perfectly acceptable input. For the sake of keeping solution simple, I would suggest to simply ask user to input number of values to compare, before reading values themselves.

Looping with for

An alternate implementation you can consider is to use a for-loop:

for (int value = readInt(" ? "); value != SENTINEL; count++, value = readInt(" ? ")) {
    min = Math.min(min, value);
    max = Math.max(max, value);
}

I find that it communicates the steps slightly clearer:

  1. initialize value
  2. Loop if value != SENTINEL
  3. increment count and read the next input for value

The other minor point I can suggest is mentioned by @mnhg too, which is to initialize min and max to the appropriate default values so that you can make the comparisons immediately.

Leave a Reply

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