3

I want to decide the arithmetic operator at run time and calculate the result of the operands. Is there a way to achieve it?

public static void main(String[] args) {

String operator = args[0];

int num1 = 10;
int num2 = 20;

int result = num1 operator num2;

System.out.println(result);

}

2 Answers2

5

If you're using JDK 1.6 or above, you can use the built-in Javascript engine like this.

public static void main(String[] args) throws Exception{
    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("JavaScript");
    String oper = args[0];
    int num1 = 10;
    int num2 = 20;
    String expr = num1 + oper + num2;
    System.out.println(engine.eval(expr));
}

Warning: As seen from this answer, it is probably not the best idea to use it. But this suited the requirement in your question the best and hence the answer.

Community
  • 1
  • 1
Rahul
  • 44,383
  • 11
  • 84
  • 103
  • 1
    Yes this would work, but it's work mentioning that eval should probably *never* be used. – Sinkingpoint Nov 27 '13 at 06:03
  • The OP want to use operator at runtime. – Masudul Nov 27 '13 at 06:04
  • @Quirliom - Could you share a link with me on why it shouldn't be used? I would love to add a proper reference along with the warning. – Rahul Nov 27 '13 at 06:04
  • @Masud - The OP wants to send the operator as an argument to the main and use it, which is exactly what the answer suggests. – Rahul Nov 27 '13 at 06:05
  • 2
    @R.J From a Purely Java stance, it's entirely out of place to include an interpreted statement, but I like [this](http://stackoverflow.com/questions/18269797/what-does-eval-do-and-why-its-evil) question which does a reasonable job. Other than that, I really like this answer. – Sinkingpoint Nov 27 '13 at 06:09
  • @Quirliom - Thanks for the heads-up. I hadn't read about it myself! :) – Rahul Nov 27 '13 at 06:16
  • 1
    +1 for entirely unthinkable approach! – Vinay Lodha Nov 27 '13 at 06:19
3

You can read it in as a String or char and then use if statements to perform the operation, like so:

public static void main(String... args) {
    String operator = args[0];

    int num1 = 10;
    int num2 = 20;

    int result = 0;

    if(operator.trim().equals("+")) {
        result = num1 + num2;
    } else if(operator.trim().equals("-")) {
        result = num1 - num2;
    } else if(operator.trim().equals("*")) {
        result = num1 * num2;
    } else if(operator.trim().equals("/")) {
        result = num1 / num2;
    }
    // More operations here...

    System.out.println(num1 + operator + num2 + "=" + result);
}

I would suggest, however, using the double datatype over int for precision's sake.

Taylor Hx
  • 2,815
  • 23
  • 36