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.");
}
}
}
break
on its own line. Single-statementif
s written on one line are confusing. Or at least separate the if from the rest with blank lines: breaking out of thewhile
is important enough to warrant an extra couple of blank lines. \$\endgroup\$