0

I'm making a calculator app and I need a way to convert a String (the numbers that the user click that appear on the display) into a double. For example this is a String:

String stringNumber="12.5/2.4+12";

And I need to put this expression into a double and calculate the result.

I have tried in this way:

double number= Double.parseDouble(stringNumber);

But obviously it doesn't work. It's because there are signs inside the expression. I need to calculate the result before the assignment.

  • 2
    do you need to code the algorithm yourself (ie is it some sort of assignment)? – DPM Sep 23 '17 at 13:05
  • Possible duplicate of https://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form – 0ddlyoko Sep 23 '17 at 13:07
  • 1
    Use exp4j there is even a tutorial for you http://www.javahelps.com/2015/03/android-simple-calculator.html – Oleg Sep 23 '17 at 13:08
  • 4
    You're nowhere near a solution. You will need a parser in general to handle an arithmetic expression. – Tim Biegeleisen Sep 23 '17 at 13:08
  • You need to implement a parser. Probably the most popular way of doing it is with Reverse Polish Notation. Here is related question and example implementation https://stackoverflow.com/questions/1320891/java-rpn-reverse-polish-notation-infix-to-postfix – Luke Sep 23 '17 at 16:46
  • @Luke Unless it is a parser exercise, the OP should not implement a parser. Java parsers for simple arithmetic expressions already exist. The OP should pick one and use it. – Patricia Shanahan Sep 24 '17 at 02:55
  • He can pick one but he can implement one for fun and experience ;) – Luke Sep 24 '17 at 10:55
  • 1
    It isn't a parser exercise, i can use a library. I'm trying the exp4j and for now it works well. Then i will try the Reverse Polish Notation. :) –  Sep 24 '17 at 11:21

0 Answers0