Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在循环中找到所有测试分数的最高、最低和平均值?_Java_Loops_Max_Average_Min - Fatal编程技术网

Java 如何在循环中找到所有测试分数的最高、最低和平均值?

Java 如何在循环中找到所有测试分数的最高、最低和平均值?,java,loops,max,average,min,Java,Loops,Max,Average,Min,下午好,或者你在读这篇文章的时候。我试图找出如何找到用户输入的最低、最高和平均测试分数。 我有一个跟踪哨兵值的循环,在我的例子中是999。因此,当用户输入999时,它将退出循环。通过检查用户输入的数据是否超过100或低于0,我还进行了一定程度的数据验证。然而,我的问题是,我如何实现一种方法,让代码找到我需要的用户输入值。我的代码如下: import java.util.Scanner; public class TestScoreStatistics { public static

下午好,或者你在读这篇文章的时候。我试图找出如何找到用户输入的最低、最高和平均测试分数。 我有一个跟踪哨兵值的循环,在我的例子中是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;
公共类TestScoreStatistics
{
公共静态void main(字符串[]args)
{
扫描仪scn=新扫描仪(System.in);
int测试分数;
双倍总分=0;
最终int QUIT=999;
final String PROMPT=“输入测试分数>>>”;
int低分;
int高分;
字符串scoreString=“”;
int计数器=0;
系统输出打印(提示);
testScore=scn.nextInt();
while(testScore!=退出)
{
如果(测试分数<0 | |测试分数>100)
{
System.out.println(“不正确输入字段”);
}
其他的
{
scoreString+=testScore+“”;
计数器++;
}
系统输出打印(提示);
testScore=scn.nextInt();
}
System.out.println(scoreString);
系统输出打印项次(计数器+“有效测试分数”);
}
}

在保持代码基本不变的同时,您可以这样做:

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
     }
import java.util.Scanner;
公共类TestScoreStatistics
{
公共静态void main(字符串[]args)
{
扫描仪scn=新扫描仪(System.in);
int测试分数;
双倍总分=0;
最终int QUIT=999;
final String PROMPT=“输入测试分数>>>”;
int lowScore=100;//将低分设置为可能的最高分
int highScore=0;//将高分设置为可能的最低分
字符串scoreString=“”;
int计数器=0;
系统输出打印(提示);
testScore=scn.nextInt();
while(testScore!=退出)
{
如果(测试分数<0 | |测试分数>100)
{
System.out.println(“不正确输入字段”);
}
其他的
{
scoreString+=testScore+“”;
计数器++;
//如果testScore低于lowScore,则获取新的最低分数
如果(测试分数<低分数){
lowScore=测试分数;
}
//如果testScore高于highScore,则获得新的最高分数
如果(测试分数>高分){
高分=测试分数;
}
totalScore+=testScore;//将所有分数相加
}
系统输出打印(提示);
testScore=scn.nextInt();
}
double averageScore=totalScore/计数器;//获取平均值
}

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

我将这样做

// defines your prompt
private static String PROMPT = "Please enter the next number> ";

// validation in a separate method
private static int asInteger(String s)
{
    try{
        return Integer.parseInt(s);
    }catch(Exception ex){return -1;}
}

// main method
public static void main(String[] args)
{

    Scanner scn = new Scanner(System.in);
    System.out.print(PROMPT);
    String line = scn.nextLine();

    int N = 0;
    double max = 0;
    double min = Integer.MAX_VALUE;
    double avg = 0;
    while (line.length() == 0 || asInteger(line) != -1)
    {
        int i = asInteger(line);
        max = java.lang.Math.max(max, i);
        min = java.lang.Math.min(min, i);
        avg += i;
        N++;

        // new prompt
        System.out.print(PROMPT);
        line = scn.nextLine();
    }
    System.out.println("max : " + max);
    System.out.println("min : " + min);
    System.out.println("avg : " + avg/N);
}
验证方法(在其当前实现中)将允许输入任何整数。一旦输入了无法转换为数字的任何内容,它将返回-1,这将触发主循环中断

主循环简单地跟踪当前运行的总数(计算平均值),以及迄今为止看到的最大值和最小值


一旦退出循环,这些值只需打印到
系统。输出

,只需对代码进行最小更改:

public class Answer {

    public static void main(String[] args) {

        Scanner scn = new Scanner(System.in);
        int testScore;
        final int QUIT = 999;
        final String PROMPT = "Enter a test score >>> ";
        int maxScore = Integer.MIN_VALUE;
        int minScore = Integer.MAX_VALUE;
        double totalScore = 0;
        double avgScore = 0.0;
        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 {
                counter++;
                System.out.println("The number of scores you entered is " + counter);
                //test for minimum
                if(testScore < minScore) minScore = testScore;
                System.out.println("Current minimum score = " + minScore);
                //test for maximum
                if(testScore > maxScore) maxScore = testScore;
                System.out.println("Current maximum score = " + maxScore);
                //calculate average
                totalScore += testScore;
                avgScore = totalScore / counter;
                System.out.println("Current average score = " + avgScore);
            }

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

        }
    }
}
公共类答案{
公共静态void main(字符串[]args){
扫描仪scn=新扫描仪(System.in);
int测试分数;
最终int QUIT=999;
final String PROMPT=“输入测试分数>>>”;
int maxScore=整数.MIN_值;
int minScore=Integer.MAX_值;
双倍总分=0;
双avgScore=0.0;
int计数器=0;
系统输出打印(提示);
testScore=scn.nextInt();
while(testScore!=退出){
如果(测试分数<0 | |测试分数>100){
System.out.println(“不正确输入字段”);
}否则{
计数器++;
System.out.println(“您输入的分数为”+计数器);
//最小值试验
如果(testScoremaxScore)maxScore=testScore;
System.out.println(“当前最大分数=”+maxScore);
//计算平均数
totalScore+=测试分数;
avgScore=总分/计数器;
System.out.println(“当前平均分数=”+avgScore);
}
系统输出打印(提示);
testScore=scn.nextInt();
}
}
}

是否允许您使用一些java-8功能?尝试查看
ArrayList
如果允许,则可以将分数存储到列表实现中,然后可以执行
IntSummaryStatistics summaryStatistics=myList.stream().collect(Collectors.SummaryInt(Integer::intValue))
然后使用
int max=summaryStatistics.getMax();int min=summaryStatistics.getMin();double average=summaryStatistics.getAverage();
收集结果,这是一个非常优雅但简单的解决方案