简体   繁体   English

我如何在Java中创建命令行条目的限制

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

My program allows you to enter a number and press enter. 我的程序允许您输入数字,然后按Enter。 Then the program asked you to give it another number up till you get to 21 numbers. 然后程序要求您再给它一个数字,直到得到21个数字。 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. 如果用户键入的不是“ q”或“ Q”之外的其他InputMismatchException也不是有效数字),则将引发InputMismatchException 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. 您的其余代码无需更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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