Write a program that reads an unspecified number of integer arguments from the command line and adds them together to print the result.
For example, suppose that you enter the following:
java Adder 1 3 2 10
The program should display 16 and then exit. The program should display an error message if the user enters only one argument.
For example, suppose that you enter the following:
java Adder 1 3 2 10
The program should display 16 and then exit. The program should display an error message if the user enters only one argument.
Solution:
public class CommandLineReader { public static void main(String args[]){ <//Checking the number of received arguments. if(args.length<2){ System.out.println("Please input more then one argument."); return; } //Adding the arguments. int sum=0; for(int i=0;i<args.length;i++){ sum+=Integer.parseInt(args[i]); } //Printing the result. System.out.println("Sum: "+sum); } }
No comments:
Post a Comment