Pregunta

I am trying to write a method in Java that accepts a string as an argument. Now this string may be a mathematical expression or it may be just an ordinary string. I have to evaluate it only if it is a mathematical expression and leave it alone if it isn't. I'll evaluate the mathematical expression using java script engine as follows:

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String foo = "1+2*10";
System.out.println(engine.eval(foo));

But the problem is if I pass a string that is not a mathematical expression, this throws an exception. I don't want exceptions in my code. What I am trying to achieve is something like this:

if(isExpression(foo))
{
engine.eval(foo);
}

This way I check whether it is a mathematical expression or not before evaluating it. Is there an easy implementation of the method isExpression(foo)? May be using some regular expression? Please let me know if there is any. Thanks

¿Fue útil?

Solución

For really complex operations like this, the effort to see if it is a valid formula is almost as much as the effort to actually do the evaluation.

I recommend that you just try to evaluate and, on a failure, throw a domain specific exception, say a CannotEvaluateFormulaException, and catch it.

Otros consejos

Q: Is there a built-in Java function to evaluate that 1+2*10 is an expression, and AB@C#! isn't?

A: No.

Using a regex might get you close, but somebody needs to parse and try to evaluate the string before you can determine whether or not it's truly an arithmetic expression.

SUGGESTION:

Call your engine, and catch any exceptions.

PS:

You should be doing that anyway, independent of "valid expression/not expression". Correct?

It's maybe possible to write a regex that checks this, but it's going to be a very long and complicated one. What you usually do, is parse, perhaps recursively, and when somethinh doesn't fit, deep down in some subpart of the expression, you throw an exception.

No shame in throwing exceptions as long as you catch them, that's what they are for! Of course there is some overhead in throwing and catching an exception, but you have to evaluate that against your initial pre-check, that will be run for all expressions, correct or not.

That said, have a look at the Interpreter Pattern to evaluate your expression, if no one has a better ready-made suggestion, especially if you have plain normal mathematical expressions with no custom extensions/logic/whatever (Check out for example @user1264811 solution!)

you need a try and catch.

refer to exception handling

You might want to check this out if your looking to make a calculator of some sort: users.cis.fiu.edu/~weiss/dsj2/code/Evaluator.java

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top