简体   繁体   English

如何在Java中从命令行平均数

[英]How to Average Numbers from Command Line in Java

This is a school assignment. 这是学校的作业。 I truly want to understand what I am doing. 我真的很想了解我在做什么。 We are instructed to make a program in Java that runs from the command line. 我们被要求制作一个从命令行运行的Java程序。 After a user enters numbers the program should then start, send a welcome message, and then tell the user what the average of his numbers is. 用户输入数字后,程序应启动,发送欢迎消息,然后告诉用户其数字的平均值是多少。

I believe the point of this is to illustrate how args is used in the program and to help familiarize us with Java. 我相信这是为了说明程序中如何使用args并帮助我们熟悉Java。

This is the explanation I have currently. 这是我目前的解释。 I can run this from the command line, I know how to add a welcome message as well... But I do not understand the code well enough to be able to add in the ability to average the numbers when a user adds the arguments. 我可以从命令行运行此命令,我也知道如何添加欢迎消息...但是我对代码的理解不够充分,无法在用户添加参数时添加平均数的功能。

public class ArgumentExample {

    public static void main(String[] args) {

        if( args.length == 1 || args.length > 1 ){
            System.out.println( args[0]);
        }

        if( args.length > 1 ) {
            for( int i = 1; i < args.length; i++ ){
                System.out.println(args[i]);
            }
        }
    }
}
public class ArgumentExample {

        public static void main(String[] args) {
            int i = 0; // declare a counter here so you can use it in the catch
            double tot = 0.0d; // declare the accumulator variable
            try {
                for (i = 0; i < args.length; i++) { // iterate over arguments...if only one is present returns just that one
                    tot += Double.parseDouble(args[i]); // sum
                }
            } catch (Exception ex) {
                System.out.println("Argument " + i + " is not a number");// print which argument is not a number if any
            }
            System.out.println("Sum is: " + tot/(args.lenght == 0 ? 1 : args.lenght); // final print statement
        }
    }

Right now you are simply printing out the arguments that are put into the args array for you. 现在,您只是为您打印出放入args数组的args It's not a big step from there to transforming the String arguments into numbers (say, doubles), adding those to a running sum in the loop, and dividing by the number of arguments after the loop: 从那里将String参数转换为数字(将其加倍),然后将其添加到循环中的运行总和中,然后除以循环后的参数数量,这并不是什么大步骤:

    double sum = 0;
    if (args.length >= 1) {
        for (int i = 0; i < args.length; i++) {
            sum += Double.parseDouble(args[i]);
        }
        System.out.println("Average = " + sum/args.length);
    }

Double is the wrapper class for the primitive type double. Double是原始类型double的包装器类。 It has the convenient method parseDouble to which you can pass a String and it will try to convert it to a double type. 它具有方便的方法parseDouble ,您可以将String传递给该方法,它将尝试将其转换为double类型。 We should use doubles here instead of ints because of the higher precision of doubles - eg if you divide 5/2 you get 2, not 2.5, unless you make sure the 5 and 2 are treated as doubles. 由于双精度较高,因此我们应在此处使用双精度而不是整数-例如,如果将5/2除以,则得到2,而不是2.5,除非确保将5和2视为双精度。

Note that this has no error checking so it will fail by throwing an exception if any of the arguments is not parseable to a Double. 请注意,这没有错误检查,因此如果任何参数都无法解析为Double,则抛出异常将失败。

args is a reference to the String array that holds all of the arguments passed into the program when it is started. args是对String数组的引用,该数组保存了程序启动时传递给程序的所有参数。

Arrays use a 0 base system for referencing the object in that position, so args[0] is the first argument passed to the program. 数组使用0基本系统引用该位置的对象,因此args[0]是传递给程序的第一个参数。

The for( int i = 1; i < args.length; i++ ) loop is going through the array until it reaches the end ( i = length - 1 ) after printing each argument for( int i = 1; i < args.length; i++ )循环遍历数组,直到在打印每个参数后到达末尾( i = length - 1 )

Students tend to put too much stuff into main. 学生们倾向于在主课上投入过多的东西。

I'd recommend that you put the real work into sensible methods that you might use someday and pass data in and out, like this: 我建议您将真实的工作放到明智的方法中,以便您有朝一日可以使用它们,然后将数据传入和传出,例如:

public class StatisticsUtils {
    public double average(double [] values) {
        double average = 0.0;
        if ((values != null) && (values.length > 0)) {
            for (double value : values) {
                average += value;
            }
            average /= values.length; 
        }
        return average;
    }
}

To get the average of the numbers you have to build the sum of them and then divide through the number of arguments. 要获得数字的平均值,您必须建立它们的总和,然后除以参数数量。 For example 例如

public class ArgumentExample 
{
  public static void main(String[] args) {

  int sum = 0;

  // step through all arguments
  for(String arg : args)
  {
    try
    {
      // try to convert the argument to an integer
      int number = Integer.parseInt(arg);
      // sum it
      sum += integer;
    }
    catch(NumberFormatException e)
    {
      // the currently processed argument couldn't be converted
      // to a number
      System.out.println(arg + " is not a number");
    }
  }

  // average = sum / valuecount
  double average = sum / args.length;

  System.out.println("average = " + average);
}

java -jar ArgumentExample 1 2 3 4 5 would result into 3. Hope that helps java -jar ArgumentExample 1 2 3 4 5将结果为3。希望有帮助

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

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