gpt4 book ai didi

java - 如何找到循环内所有测试分数的最高、最低和平均值?

转载 作者:行者123 更新时间:2023-12-02 11:36:16 24 4
gpt4 key购买 nike

下午好,或者当您阅读本文时。我试图弄清楚如何找到用户输入的测试分数的最小值、最高值和平均值。我有一个循环跟踪哨兵值,在我的例子中是 999。因此,当用户输入 999 时,它会退出循环。我还通过检查用户是否输入超过 100 或低于 0 作为输入来进行一定程度的数据验证。但是,我的问题是,如何实现一种方法来获取此代码来查找用户输入所需的值。我的代码如下:

import java.util.Scanner;
public class TestScoreStatistics
{

public static void main(String[] args)
{
Scanner scn = new Scanner(System.in);
int testScore;
double totalScore = 0;
final int QUIT = 999;
final String PROMPT = "Enter a test score >>> ";
int lowScore;
int highScore;
String scoreString = "";
int counter = 0;

System.out.print(PROMPT);
testScore = scn.nextInt();

while (testScore != QUIT)
{

if (testScore < 0 || testScore > 100 )
{
System.out.println("Incorect input field");

}
else
{
scoreString += testScore + " ";
counter++;
}

System.out.print(PROMPT);
testScore = scn.nextInt();



}
System.out.println(scoreString);
System.out.println(counter + " valid test score(s)");

}

}

最佳答案

在保持代码几乎相同的同时,您可以这样做:

import java.util.Scanner;
public class TestScoreStatistics
{

public static void main(String[] args)
{
Scanner scn = new Scanner(System.in);
int testScore;
double totalScore = 0;
final int QUIT = 999;
final String PROMPT = "Enter a test score >>> ";
int lowScore = 100; //setting the low score to the highest score possible
int highScore = 0; //setting the high score to the lowest score possible
String scoreString = "";
int counter = 0;

System.out.print(PROMPT);
testScore = scn.nextInt();

while (testScore != QUIT)
{

if (testScore < 0 || testScore > 100 )
{
System.out.println("Incorect input field");

}
else
{
scoreString += testScore + " ";
counter++;
//getting the new lowest score if the testScore is lower than lowScore
if(testScore < lowScore){
lowScore = testScore;
}
//getting the new highest score if the testScore is higher than highScore
if(testScore > highScore){
highScore = testScore;
}
totalScore += testScore; //adding up all the scores
}

System.out.print(PROMPT);
testScore = scn.nextInt();
}
double averageScore = totalScore / counter; //getting the average
}

这将检查 testScore 是否高于或低于最高分数和最低分数。该程序还将所有分数加在一起,然后除以计数器(即有多少个测试)以获得平均值。

关于java - 如何找到循环内所有测试分数的最高、最低和平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48911837/

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