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);
}