0

I am creating a program that is basically a calculator, which takes in input from the user and breaks it into different parts. Example input:

4 + 5

My program takes that input and analyzes it and breaks down the terms, the operators, omits white space, and some other things. However, when I put all the pieces back together, they are in a String form. So it looks like this:

"4+5"

How can I have the program take that string and parse it to yield the int 9?

I tried Integer.parseInt(input) , and to no surprise, it returns an error. So is there a simple (enough) way to do this? Or will I have to create my own method to parse the equation?

By the way, it can do more than two terms, and the reason I break down the input is to check for input errors, such as 5 ++ 5 or anything of that manner. It is also to incorporate PEMDAS.

Justin Reusnow
  • 290
  • 3
  • 9
  • 2
    [possible duplicate](http://stackoverflow.com/q/15173681/1113392) – A4L Dec 20 '13 at 22:42
  • 2
    And this: http://stackoverflow.com/questions/4173623/mathematical-expression-string-to-number-in-java – Tim B Dec 20 '13 at 22:44
  • You want to use the shunting-yard algorithm. You use a stack for the operators, and a queue for the values. Then you can iterate through the two of them to know which order the calculations are in, and also follow the 'order of operations' rules. – Brant Unger Dec 20 '13 at 23:10

1 Answers1

1

There's really no way that I know of to do this simply without changing your current code. What you'd probably have to do is check the string for instances of operator characters ('+', '*', etc.) and use the split method to separate out the numbers, which you can then parse individually into ints, and then combine using the operators.

Alternately, if it's at all possible, just leave a single space between each number and the preceding/trailing operator, and split around instances of ' '.

Patrick N
  • 133
  • 1
  • 5