In: Computer Science
Write a program that prints the sum of its command-line arguments (assuming they are numbers).
For example,
java Adder 3 2.5 -4.1
should print The sum is 1.4
import java.text.DecimalFormat;
//class definition
public class Adder {
//main class definition
public static void main(String[] args) {
//eclare and initialise variable to
store sum and number converted from string
double sum = 0, num=0;
//for loop to read command line
arguments
for(int i=0;i<args.length;i++)
{
//Convert
argument from string to double
num =
Double.parseDouble(args[i]);
//calculate the
sum
sum = sum +
num;
}
//create a decimal formal object to
help round result to 2 decimal places
DecimalFormat format = new
DecimalFormat("0.0");
//Print the result with the help of
format object
System.out.println("The sum is " +
format.format(sum));
}
}
OUTPUT