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); } 
1
  • May be you can. But at this point you need to work with compiled bytecode. Commented Nov 27, 2013 at 6:00

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Yes this would work, but it's work mentioning that eval should probably never be used.
The OP want to use operator at runtime.
@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.
@R.J From a Purely Java stance, it's entirely out of place to include an interpreted statement, but I like this question which does a reasonable job. Other than that, I really like this answer.
+1 for entirely unthinkable approach!
|
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.

Comments