Posted In: Java Core, String

How to parse a mathematical expression given as a string – using ScriptEngine

Evaluating a math expression given in string form


package com.example.mathexpression;

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

import org.junit.Test;

public class MathExpression2 {

	@Test
	public void evaluate1() throws Exception {
		System.out.println("\nevaluate1() start");
		ScriptEngineManager mgr = new ScriptEngineManager();
		ScriptEngine engine = mgr.getEngineByName("JavaScript");
		String result = "5+4*(7-15)";
		System.out.println(engine.eval(result));
	}
}

Tags:

by , on August 30th, 2017

  • Categories