Question: 7.12.1: Compute the value of an arithmetic expression with exception handling. Write a method that computes the value of an arithmetic expression. The operator string
7.12.1: Compute the value of an arithmetic expression with exception handling. Write a method that computes the value of an arithmetic expression. The operator string should be one of ("+", "-", "*", or "/"). The method should throw an IllegalArgumentException otherwise. Also throw an IllegalArgumentException if the operator is "/" and the second argument is zero.
Arithmetic.java
public class Arithmetic { /** Computes the value of an arithmetic expression @param value1 the first operand @param operator a string that should contain an operator + - * or / @param value2 the second operand @return the result of the operation */ public static int compute(int value1, String operator, int value2) { if (operator.equals("+")) { return /* Your code goes here */; } else if (operator.equals("-")) { return /* Your code goes here */; } else if (operator.equals("*")) { return /* Your code goes here */; } else if (operator.equals("/")) { /* Your code goes here */ } else { /* Your code goes here */ } } }
---------------------------------------------------------------
ArithmeticTester.java
public class ArithmeticTester { public static void main(String[] args) { call(3, "+", 4, "7"); call(3, "-", 4, "-1"); call(3, "*", 4, "12"); call(3, "@", 4, "java.lang.IllegalArgumentException"); call(13, "/", 4, "3"); call(13, "/", 0, "java.lang.IllegalArgumentException"); }
public static void call(int a, String op, int b, String expected) { try { System.out.print("compute(" + a + " " + op + " " + b + "): "); System.out.flush(); System.out.println(Arithmetic.compute(a, op, b)); } catch (Throwable ex) { System.out.println(ex.getClass().getName()); } System.out.println("Expected: " + expected + " "); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
