0

Java code...

If I have

int num = 10 + 5;
System.out.println(num);

The result is 15

And if I have

String str = "10";
int number = Integer.parseInt(str);
System.out.println(number);

The result is 10

But if I have

String str = "10 + 5"; //here the problem.
int number = Integer.parseInt(str);
System.out.println(number);

The result is error message.

How to do it correctly. What I want to implement is to take expression from a String and calculate it. I am forced to take it from a String because I take it from JTextfield, so I want to make the calculation for the returned String expression.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
Saleh Feek
  • 2,048
  • 8
  • 34
  • 56
  • 2
    You need to parse the expression. See here for one solution: http://stackoverflow.com/questions/3422673/java-evaluate-string-to-math-expression – cklab Aug 04 '12 at 17:53

3 Answers3

2

There is no simple way to do it directly because you need some sort of "expression evaluator". One way would be to use a javascript engine from the scripting library:

public static void main(String[] args) throws Exception {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");

    String s = "10 + 5";
    int  result = ((Double) engine.eval(s)).intValue();
    System.out.println(result); // 15
}
assylias
  • 321,522
  • 82
  • 660
  • 783
0

Looks like a similar question was already answered: Is there an eval() function in Java?

You could however write a pretty simple parser by splitting the string into an array and writing an algorithm to handle the operations.

Community
  • 1
  • 1
trousyt
  • 360
  • 2
  • 12
0

You will have to write an expression parser to separate out operands and operators and then accordingly perform the operations. You cannot pass 10 + 5 to Integer.parseInt() and expect the evaluated result.

devang
  • 5,376
  • 7
  • 34
  • 49