2

Now I hava a String lam = "(8-2*7.5)+10" ,so is there any method or class to calculate this String expression and return me the result directly?

Thanks in advance!

Rocky
  • 1,287
  • 3
  • 15
  • 37
  • 2
    You can use this link.http://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form – Rohan May 08 '13 at 07:22

3 Answers3

3

try this

    double res = (Double) new ScriptEngineManager().getEngineByName("js").eval("(8-2*7.5)+10");
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
2

java 1.6 provides Javascript engine within. You can use that to calculate your mathematical expression.

clases to be used are : ScriptEngineManager and ScriptEngine

Madhusudan Joshi
  • 4,438
  • 3
  • 26
  • 42
  • Perhaps not the solution the original poster had in mind while asking, but the most pragmatical one. (If he uses a suitable version of java) – mschenk74 May 08 '13 at 07:25
  • 1
    Ya that's true that java 6 and later provides the javascript engine which solves the problem very easily. If you have some better solution which fits to all versions of java then please do post. thanks for the feedback. – Madhusudan Joshi May 08 '13 at 07:29
1

Almost certainly not by default. This would correspond to either runtime interpretation of Java code (eeek!) or parsing and interpretation machinery for a fairly trivial arithmetic sub-language embedded within the Java standard library.

If you need to parse and evaluate expressions of this sort, I would consider writing a simple recursive-descent parser and evaluating on-the-fly. A quick Google search should suggest ways to do this in Java for languages of precisely this sort.

Gian
  • 13,735
  • 44
  • 51