-1
練習要求我計算平均值,最大值和最小值。我的代碼滿足這個目的,但是我需要在我的代碼中包含用戶輸入的考試成績必須介於0和100之間的地方。包含這個的最佳方式是什麼? 這是我的代碼。如何在我的程序中包含輸入的整數必須介於0和100之間?
import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;
public class hw
{
public static void main (String[] args)
{
int maxGrade = Integer.MIN_VALUE;
int minGrade = Integer.MAX_VALUE;
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 ++;
if(score > maxGrade)
maxGrade = score;
if(score < minGrade)
minGrade = score;
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));
System.out.println("The minimum value is " + minGrade);
System.out.println("The maximum value is " + maxGrade);
}
else
System.out.println("\nNo grades were entered");
}
}
謝謝!
您在哪裏(以及如何)防止處理'SENTINEL'?這似乎是一個適當的鄰居來強制限制輸入值。 – greybeard