简体   繁体   中英

How can I find the highest, lowest, and average value of all test scores within my loop?

Good afternoon, or whenever you are reading this. I am trying to figure out how I can find the minimum, highest, and average of test scores that a user enters. I have a loop that keeps track of a sentinel value, which in my case is 999. So when the user enters 999 it quits the loop. I also have some level of data validation by checking if the user entered over 100 or under 0 as their input. However, my question is, how can I implement a way to get this code to find the values I need for my user inputs. My code is as follows:

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

    }

}

While keeping your code pretty much the same, you could do it like this:

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
     }

This will check if the testScore is higher or lower than the highest and lowest scores. This program will also add all the scores together and divide them by the counter (which is how many tests there are) to get the average.

This is how I would do this.

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

The validation method will (in its current implementation) allow any integer number to be entered. As soon as anything is entered that can not be converted into a number, it will return -1, which triggers a break from the main loop.

The main loop simply keeps track of the current running total (to calculate the average), and the maximum and minimum it has seen so far.

Once the loop is exited, these values are simply printed to System.out .

With minimal changes of your code:

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

        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM