Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Java program question (Passing Strings to the main Method) Suppose you are to de

ID: 3668826 • Letter: J

Question

Java program question

(Passing Strings to the main Method) Suppose you are to develop a program that performs arithmetic operations ( + - * / ) on integers. The program receives an expression in one string argument. The expression consists of an integer followed by an operator and another integer. For example, to add two integers, use this command: java Calculator "2 + 3" //don’t forget the double quotation mark The program will display the following output: 2 + 3 = 5 The expression must be entered in the form of “operand1 operator operand2”. The operands and operator are separated by exactly one space. The strings passed to the main program are stored in args, which is an array of strings. In this case, we pass the expression as one string. Therefore, the array contains only one element in args[0] and args.length is 1. Here are the steps in the program: Use args.length to determine whether the expression has been provided as one argument in the command line. If not, terminate the program using System.exit(1). Split the expression in the string args[0] into three tokens, token[0], token[1] and token[2] using split method with space as delimiter. Perform a binary arithmetic operation on the operands token[0] an token[2] using operator in token[1]. Converts a digital string into an integer using Integer.parseInt. For example Integer.parseInt(token[0]). If the string doesn’t consist of digits, the program will terminate abnormally.

Explanation / Answer

/**
* @author Srinivas Palli
*
*/
public class ArithmeticExpression {

   /**
   * @param args
   */
   public static void main(String[] args) {

       try {

           if (args.length != 1) {

               System.exit(1);
           }

           String token[] = args[0].split(" ");

           int num1 = Integer.parseInt(token[0]);
           int num2 = Integer.parseInt(token[2]);

           if (token[1].equals("+")) {

               System.out.println(args[0] + " = " + (num1 + num2));
           } else if (token[1].equals("-")) {

               System.out.println(args[0] + " = " + (num1 - num2));
           } else if (token[1].equals("*")) {

               System.out.println(args[0] + " = " + (num1 * num2));
           } else if (token[1].equals("/")) {

               System.out.println(args[0] + " = " + (num1 / num2));
           }

       } catch (Exception e) {
           // TODO: handle exception
       }

   }
}

OUTPUT:

2 + 3 = 5

2 - 3 = -1

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote