2016-11-05 4 views
0

Der erste Teil der Übung bestand darin, den Testergebnisdurchschnitt zu berechnen. Das nächste Problem hat mich gebeten, dieses Problem aufzubauen und das Minimum und Maximum zu berechnen. Kann mir jemand helfen? Das ist bisher mein Code.Berechnung eines Minimum und Maximum in Java?

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"); 
    } 

    } 

Antwort

1

in Ihrer while Schleife, können Sie den aktuellen Spielstand auf das Maximum und das Minimum vergleichen.

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(); 
} 

Sie müssen auch den max und min bis auf ihren "gegenüber" Wert (wenn sie zu deklarieren):

int maxGrade = Integer.MIN_VALUE; 
int minGrade = Integer.MAX_VALUE; 
Verwandte Themen