简体   繁体   中英

Displaying min, max, average, and numbers entered

This is what i've got so far, but can't figure out how to display the number of numbers the user enters, I know it has something to do with the count method, but can't figure out how to implement it into this.

import java.util.Scanner;

public class Test {

    @SuppressWarnings("resource")
    public static void main(String[] arg) {
        int count = 0;
        double sum = 0;
        double maximum = 0;
        double minimum = 100;

        Scanner kb = new Scanner(System.in);

        double input = -1;
        // Main processing loop...
        do {

            // Validation loop...
            do {
                System.out.println("Please enter a number or 0 to quit:");
                input = kb.nextDouble();
                kb.nextLine();
            } while (input > 100);

            if (input > 0) {
                count++;
                sum += input;

                if (maximum < input) {
                    maximum = input;
                }

                if (minimum > input) {
                    minimum = input;
                }
            }
        } while (input != 0);

        double average = (sum / count);

        System.out.println(
                        "The average is: " + average);
        System.out.println(
                        "Minimum of entered numbers: " + minimum);
        System.out.println(
                        "Maximum of entered numbers: " + maximum);

    }

}

Add the entered items to a List.

You create a list with:

List<Integer> list = new ArrayList<>();

And you add an item to the list with:

list.add(input);

Finally you have the collection of all the inputs and better to work with.

The advantage is you can return back to all the inputs and work with them again.

To get the size you can use both of:

System.out.println(count);       -- using your variable
System.out.println(list.size()); -- get from the list

If you're trying to work with the input you need to save it somewhere. An array would be your best choice (array, ArrayList, ...).

  1. Iterate through the array to get the lowest and highest number.
  2. Divide the sum of all numbers by the size of the array to get the average.

EDIT: If you want to add negative numbers change if (input > 0) to if (input != 0) (I'm guessing you're adding the input into the array from here).

just change the if condtion logic use if (input != 0 ) { instead of if if(input > 0 )

try like below.

              if (input != 0 ) {
....
}

System.out.println("User enters total Numbers: "+count);

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