A. Moore - 1 year ago 103
Java Question

# Calculating a Minimum and Maximum in Java?

The first part of the exercise was to calculate the test score average. The next problem asked me to build off this problem and calculate the minimum and maximum. Can anyone help me? This is my code so far.

`````` import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;

public class hw
{
public static void main ( String[] args )
{
int maxGrade;
int minGrade;
int count=0;
int total=0;
final int SENTINEL = -1;
int score;

Scanner scan = new Scanner( System.in);
System.out.println( "To calculate the class average, enter each test
score.");
System.out.println( "When you are finished, enter a -1.");

System.out.print( "Enter the first test score > ");
score = scan.nextInt();

while (score != SENTINEL )
{
total += score;
count ++;

System.out.print("Enter the next test score > ");
score = scan.nextInt();
}
if (count != 0)
{
DecimalFormat oneDecimalPlace = new DecimalFormat("0.0");
System.out.println( "\nThe class average is "
+ oneDecimalPlace.format( (double) (total) / count ));
}
else
System.out.println("\nNo grades were entered");
}

}
``````

Answer Source

in your `while` loop, you can compare the current score to the maximum and the minimum.

``````while (score != SENTINEL )
{
total += score;
count ++;
if(score > maxGrade)
maxGrade = score;
if(score < minGrade)
minGrade = score;
System.out.print("Enter the next test score > ");
score = scan.nextInt();
}
``````

You also need to set the max and min (when declaring them) to their "opposite" value:

``````int maxGrade = Integer.MIN_VALUE;
int minGrade = Integer.MAX_VALUE;
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download