gpt4 book ai didi

java - 如何从计算最高数和平均值中排除某个范围内的输入数?

转载 作者:行者123 更新时间:2023-12-02 04:32:56 26 4
gpt4 key购买 nike

在我的程序中,我试图让用户输入不确定数量的成绩,介于 0 和 100 之间,如果低于 0 或超过 100,它会显示错误消息,直到用户输入“999”,然后显示输入的分数、最高分数、最低分数和平均分数。

程序中的所有内容都可以正常工作,但是我无法弄清楚如何排除“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);
}
}
}

最佳答案

你有两个额外的循环,我会从一个无限循环开始,检查 999 和有效性,然后增加值(并更新 highestlowest 等)。喜欢,

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

关于java - 如何从计算最高数和平均值中排除某个范围内的输入数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46922957/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com