Search code examples
javastringmethodsthrowarithmetic-expressions

how to use the a string value for arithmetic equations?


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

Solution

  • 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.