2016-11-05 110 views
0

練習的第一部分是計算測試分數的平均值。接下來的問題要求我建立這個問題並計算最小值和最大值。誰能幫我?這是我的代碼到目前爲止。在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"); 
    } 

    } 

回答

1

while循環,您可以比較當前比分的最大值和最小值。

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

您還需要設置最大值和最小值(聲明他們的時候),他們的「相對」值:

int maxGrade = Integer.MIN_VALUE; 
int minGrade = Integer.MAX_VALUE; 
相關問題