-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