wuno wuno - 5 months ago 10
Java Question

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. 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.

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

Answer
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
        }
    }