Showing posts with label formatting decimal output in Java. Show all posts
Showing posts with label formatting decimal output in Java. Show all posts

Sunday, 13 September 2020

Java program to find the average of n numbers given as input in the command line argument.

 In Java programs, the simplest way to give input is to pass in the values along the command line while executing the program. This program finds the average of n numbers. The input given in the command line is assigned to the arg[ ] array as strings. To know the number of inputs, arg.length is used. Each element in the arg[ ] array is converted into an integer using the Integer.parseInt( ) function where Integer is a predefined wrapper class. If the input is a floating-point value then use Double.parseDouble() function to convert the command line string values to the corresponding floating-point values.

Note: The program uses the DecimalFormat class function format( ) to format the decimal output to two decimal places. This DecimalFormat class is defined in the java.text package. Hence the first line of the program imports this package.

Program

import java.text.*;
class Average
{
    public static void main(String arg[])
    {
        double sum=0,avg;
        int n=arg.length;
        DecimalFormat df = new DecimalFormat("#.##");
        for(int i=0;i<n;i++)
            sum=sum+Integer.parseInt(arg[i]);
        avg=sum/n;
        System.out.print("The average of the "+n+" numbers = ");
        System.out.println(df.format(avg));
    }
}


OUTPUT

>java Average 3 5 8 4 6 6 7 8

The average of the 8 numbers = 5.88