Question 1. Write a complete main method that does the following: 1. Takes 2 command line arguments, both integers. 2. If there are not 2 arguments, throw an IllegalArgumentException with an appropriate message. 3. Otherwise, output, to the console, the sum and product of those numbers, each on a different line. For example, C:>java Question2 12 5 12 5

Respuesta :

Answer:

public class Question2 {

   public static void main(String[] arguments) {

       if (arguments.length == 2) {

           int firstInteger = Integer.parseInt(arguments[0]);

           int secondInteger = Integer.parseInt(arguments[1]);

           System.out.println(firstInteger + " + " + secondInteger + " = " + (firstInteger + secondInteger));

           System.out.println(firstInteger + " * " + secondInteger + " = " + (firstInteger * secondInteger));

       } else {

           throw new IllegalArgumentException();

       }

   }

}

Explanation:

  • Inside the main method, check whether the length of arguments is equal to 2, and then store the arguments in the variables called firstInteger and secondInteger respectively.
  • The next step is to display the sum and product of both firstInteger and secondInteger inside the if block.
  • Otherwise, if the length of arguments is not equal to 2, then throw an IllegalArgumentException.