java - how to use the a string value for arithmetic equations? -
i’m trying write method computes value of arithmetic expression. method takes 2 int parameters value1 , value2 , string parameter operator. i’m suppose throw illegalargumentexception if operator isn’t *, /, -, or + or if / followed value2 of 0.
how string value work in arithmetic expression? far code 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 0 error"); } int result; return result = (value1 + operator + value2); }
i think best option switch case, see 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 0 handle divide 0 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 case default case replace first if check , able remove it.
Comments
Post a Comment