patternjavaMinor
Stanford CS106A Min / Max program
Viewed 0 times
stanfordprogramcs106aminmax
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
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
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.Context
StackExchange Code Review Q#87313, answer score: 5
Revisions (0)
No revisions yet.