在我的程序中,我试图让用户输入不确定数量的等级,介于0和100之间,如果它低于0或超过100,则会出现错误消息,直到用户输入" 999",然后显示输入的成绩数,最高数字,最低数字和平均数。
我让程序中的所有内容都有效,但我无法弄清楚如何排除" 999"结束了用户能够输入最高等级和平均值的数字。
这是我的代码:
import java.util.Scanner;
public class TestScoreStatistics
{
public static void main(String[] args)
{
int numberOfScores = 0;
int highest = 0;
int lowest = 100;
double average;
Integer score = 0;
int sumOfScores = 0;
Scanner input = new Scanner(System.in);
System.out.println("Please enter a grade or enter 999 to finish >> ");
score = input.nextInt();
sumOfScores = sumOfScores + score;
while (score != 999 && score <= 100 && score >= 0)
{
System.out.println("Please enter a grade or enter 999 to finish >> ");
score = input.nextInt();
sumOfScores = sumOfScores + score;
++numberOfScores;
if(score > highest){
highest=score;}
else if(score<lowest){
lowest=score;}
}
while (score != 999 && score > 100 || score < 0)
{
System.out.println("You entered an invalid score. Please enter a valid test score.");
System.out.println("Please enter a grade or enter 999 to finish >> ");
score = input.nextInt();
sumOfScores = sumOfScores + score;
}
if (score == 999)
{
System.out.println("Number of Scores you entered: " + numberOfScores);
System.out.println("Highest Score: " + highest);
System.out.println("Lowest Score: " + lowest);
average = sumOfScores / numberOfScores;
System.out.println("Average Score: " + average);
}
}
}
答案 0 :(得分:0)
你有两个额外的循环,我将以无限循环开始,检查999
和有效性,然后递增值(并更新highest
和lowest
等)。像,
public static void main(String[] args) {
int numberOfScores = 0, highest = 0, lowest = 100;
int sumOfScores = 0;
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Please enter a grade or enter 999 to finish >> ");
int score = input.nextInt();
if (score == 999) {
break; // <-- end the loop
} else if (score > 100 || score < 0) {
System.out.println("You entered an invalid score. "
+ "Please enter a valid test score.");
} else {
sumOfScores += score;
numberOfScores++;
highest = Math.max(highest, score);
lowest = Math.min(lowest, score);
}
}
System.out.println("Number of Scores you entered: " + numberOfScores);
System.out.println("Highest Score: " + highest);
System.out.println("Lowest Score: " + lowest);
double average = sumOfScores / (double) numberOfScores;
System.out.println("Average Score: " + average);
}