简体   繁体   中英

how do i create a limit of command line entries in java

My program allows you to enter a number and press enter. Then the program asked you to give it another number up till you get to 21 numbers. the point is it gives you the average of your numbers. If you wanted you can enter as many numbers on one entry and it will still work. How can I make it so you can only enter one number at a time?

Also how can I stop any entries besides numbers from being added?

import java.util.ArrayList;
import java.util.Scanner;

class programTwo
{   
    private static Double calculate_average( ArrayList<Double> myArr )
    {
        Double sum = 0.0;
        for (Double number: myArr)
        {
            sum += number;
        }
        return sum/myArr.size(); // added return statement
    }

    public static void main( String[] args )
    {
        Scanner scan = new Scanner(System.in);
        ArrayList<Double> myArr = new ArrayList<Double>();
        int count = 0;
        System.out.println("Enter a number to be averaged, repeat up to 20 times:");
        String inputs = scan.nextLine();

    while (!inputs.matches("[qQ]") )
    {

        if (count == 20)
        {
            System.out.println("You entered more than 20 numbers, you suck!");
            break;
        }

        Scanner scan2 = new Scanner(inputs); // create a new scanner out of our single line of input
        myArr.add(scan2.nextDouble());
        count += 1;
        System.out.println("Please enter another number or press Q for your average");

        inputs = scan.nextLine();
    }
    Double average = calculate_average(myArr);
    System.out.println("Your average is: " + average);
}}

If a user types something other than a "q" or "Q", which is also not a valid number, then an InputMismatchException will be thrown. You just need to catch that exception, display an appropriate message, and ask the user to continue. This can be done as follows:

try {
    myArr.add(scan2.nextDouble());
    count += 1;
} catch (InputMismatchException e) {
    System.out.println("Very funny! Now follow the instructions, will you?");
}

The rest of your code need not change.

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