0

I’m trying to write a method that computes the value of an arithmetic expression. The method takes two int parameters value1 and value2 and a string parameter operator. I’m suppose to throw an IllegalArgumentException if the operator isn’t *, /, -, or + or if / is followed a value2 of 0.

How would I get a string value to work in an arithmetic expression? So far this is the code I have:

  public static int compute(int value1, String operator, int value2)
  {
  if ((!operator.equals("+")) || (!operator.equals("*")) || 
     (!operator.equals("-")) || (!operator.equals("/")))
     {
        throw new IllegalArgumentException("Invalid Operator");
     }
  if ((operator.equals("/")) && (value2 == 0))
     {
        throw new IllegalArgumentException("Divide by 0 error");
     }
     int result; 
     return result = (value1 + operator + value2);
  }
JURO312
  • 69
  • 5
  • 2
    `if(operator.equals("+")) result = value1+value; else if(....`, otherwise use a `String` [and parse the whole expresseion](https://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form) – SomeJavaGuy Jul 26 '17 at 05:27
  • Thank you, I was able to get my program to work. – JURO312 Jul 26 '17 at 05:33

1 Answers1

4

I think best option for you is switch case, see this example code:

int result;

switch (operator)
{
    case "+":
              result = value1 + value2;
              break;
    case "-":
              result = value1 - value2;
              break;
    case "*":
              result = value1 * value2;
              break;
    case "/":
              //check if value2 is 0 to handle divide by zero exception
              if(value2 != 0)
                  result = value1 / value2; 
              else
                  System.out.println("DIVISION NOT POSSIBLE");

              break;
    default:
             throw new IllegalArgumentException("Invalid operator: " + operator);

}

return result;

And in this case the default case will replace the first If check and you will be able to remove it.

Fady Saad
  • 1,169
  • 8
  • 13