Command Line Arguments II: A Java application can accept any number of arguments from the command line.
Write a program to add 2 integers passed as command line arguments and to print their sum. If the number of command line arguments passed is not equal to 2, then print Invalid Input.
Input and Output Format:
Refer sample input and output for formatting specifications.
All text in bold corresponds to input and the rest corresponds to output.
Sample Input and Output 1:
//Type this in command line. Assume that the class name is Main
java Main 5 6
The sum of 5 and 6 is 11
Sample Input and Output 2:
//Type this in command line. Assume that the class name is Main
java Main
Invalid Input
Sample Input and Output 3:
//Type this in command line. Assume that the class name is Main
java Main 1 2 3
Invalid Input
Solution
class Main
{
public static void main(String jr[])
{
if(jr.length==2)
{ int sum = Integer.parseInt(jr[0])+Integer.parseInt(jr[1]);
System.out.println("The sum of "+jr[0]+" and "+jr[1]+" is "+sum);
}
else
System.out.println("Invalid Input");
}
}
Happy Learning – If you require any further information, feel free to contact me.