Version 2
20.09.2009 01:44:48
Dies ist die aktuelle Version
Wenn es nicht zeitkritisch ist, und man Java 1.6 verwendet, kann man das auch von JavaScript ausrechnen lassen. Das ist sehr einfach zu verwenden, und hat den Vorteil, dass man keine zusätzlichen Bibliotheken benötigt.
Ein Beispiel:
EDITIERT - siehe Kommentar
import javax.script.*;
/**
* Sample class showing how to use the JavaScript ScriptEngine
* of Java 1.6 to evaluate mathematical expressions
*/
public class Evaluator
{
public static void main(String[] args) throws Exception
{
String input = "2*(3+1-2*4)+9";
System.out.println(input+" = "+evaluate(input));
input = "Math.pow(1+1, Math.sin(Math.PI / 6))";
System.out.println(input+" = "+evaluate(input));
input = "1+1";
System.out.println(input+" = "+evaluate(input));
// Invalid input
//input = "";
//input = "x+3";
//input = "4+3)";
//input = "/4+3";
//input = "1+1==2";
//System.out.println(input+" = "+evaluate(input));
}
/**
* Evaluates the mathematical expression in the given String
* using the JavaScript ScriptEngine. Thus, the given String
* must use JavaScript syntax. Valid strings may be <br />
* <b>2*(3+4)</b> <br />
* or
* <b>Math.pow(1+1, Math.sin(Math.PI / 6))</b> <br />
* <br />
* Throws an IllegalArgumentException if a parsing error occurs
*
* @param The string containing the expression to evaluate
* @return The result of evaluating the expression
* @throws IllegalArgumentException If the String can not be
* evaluated
*/
public static double evaluate(String string)
{
ScriptEngine engine =
new ScriptEngineManager().getEngineByName("JavaScript");
try
{
Object object = engine.eval("eval("+string+")");
if ((object != null) && (object instanceof Number))
{
return ((Number)(object)).doubleValue();
}
else
{
throw new IllegalArgumentException(
"Invalid input: '"+string+"'");
}
}
catch (ScriptException e)
{
throw new IllegalArgumentException(
"Invalid input: '"+string+"'", e);
}
}
}