The code segment below finds (and prints) the minimum and maximum of values accepted as input.
Scanner fromKeyboard = new Scanner(System.in);
System.out.print("How many values (>= 1)? ");
int numValues = fromKeyboard.nextInt();
fromKeyboard.nextLine();
System.out.print("Value?: ");
int input = fromKeyboard.nextInt();
fromKeyboard.nextLine();
int min = input;
int max = input;
for(int valNum = 2; valNum <= numValues; valNum++)
{
System.out.print("Value?: ");
input = fromKeyboard.nextInt();
fromKeyboard.nextLine();
if(input < min)
min = input;
if(input > max)
max = input;
}
fromKeyboard.close();
System.out.println("Min: " + min);
System.out.println("Max: " + max);
The algorithm is the same as for finding the minimum/maximum of values from any source. The first value is accepted before the loop. Both the minimum and maximum are set to the first value that could be the minimum/maximum (the first value entered).
Extensions
The code segment above requires that the user specify the number of values before entering any values. This allows requiring at least 1 value and setting the minimum/maximum to the first thing that could be the min/max. As an alternative, values may be accepted until a sentinel is entered as in Input with a sentinel. This presents additional challenges, including choosing appropriate initial values for the min/max and limiting the range of values that can be entered.
As with many examples of finding the minimum/maximum, the user is required to enter at least 1 value. The code segment above does not attempt to validate that the user entered a value >= 1
as the number of values. See Input validation for a discussion of how to accept only valid input.
Navigation
- Find the min/max
- Find the min/max in an array of objects
- Find the min/max of a fixed number of values
- Find the min/max with calculated values