I have been thinking to solve any problem like 1+2*4-5 with user entering it and program to solve it. I've read some questions on this site about storing arithmetic operator and the solution says to check by using switch which can't be applied here. I would be thankful if anybody could suggest any idea of how to make it.
-
1Google "java expression evaluator". Your question is too broad for this site. – Bathsheba Jan 07 '15 at 12:23
-
This SO can point you in the right direction: http://stackoverflow.com/questions/4010674/looking-for-an-expression-evaluator – wassgren Jan 07 '15 at 12:35
1 Answers
I had a similar exercise not long ago, but in the question it was stated that the seperation is a space. So the user input would be 1 + 2 * 4 - 5, and i solved it that way. I will give you some tips but not paste the whole code.
-you read the input as a String
-you can use the String.split() method to devide the String into the pieces you need and they will be put in an array.(in this case: strArray[0]='1',strArray[1]='+', etc)
-you will need a for-loop to go trough every String in the array:
-the decimals will need to be converted to integers with the Integer.parseInt() method.
-The + - * / will need to be put in switch-statement. (be careful how you construct your loop, think about how many times you want to go trough it and what you need in each loop)
I hope these tips helped.

- 5
- 2