Thursday 25 November 2021

Java: How to evaluate a mathematical expression?

Using built-in Javascript engine, we can evaluate a mathematical expression.

 

Example

ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript");
String result = "(10 + 2) * 3";

 

Find the below working application.

 

ExpressionEvaluator.java

 

package com.sample.app.strings;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class ExpressionEvaluator {

	public static void main(String args[]) throws ScriptException {
		ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
		ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript");
		String result = "(10 + 2) * 3";
		System.out.println("result : " + scriptEngine.eval(result));
	}

}

Output

result : 36

 

 

 

You may like

No comments:

Post a Comment