+ 4

Evaluating a math expression in Java.

I wanted to see how a programmer can evaluate a math expression in Java, such as this: input: 10^6 8+5+6 152.53-6*(5) output: 1000000 19 122.53 However, I wanted to avoid too many if or switch statements, and avoid putting spaces between the values and the operands. How can I do such?

21st Apr 2018, 1:56 PM
Sheldon Duncan
Sheldon Duncan - avatar
6 odpowiedzi
+ 3
@Timon Paßlick Because I made a code in which was basic calculator, yet I got complaints and downvotes based on if and switch statements, plus putting spaces between the operands and the numbers. Especially considering the fact that you could only evaluate 2 numbers at a time, I felt pretty badly about the code. https://code.sololearn.com/c6onX1jZFliG/#java If and/or switch statements are a given, but I don't want the whole program to just be switch after switch after switch after switch, proving to be a useless calculator. Although I don't think there's much wrong with it, I would like to learn how to do more advanced coding, and learning how to evaluate a math expression is part of it.
21st Apr 2018, 3:58 PM
Sheldon Duncan
Sheldon Duncan - avatar
+ 2
Why do you have fear of if and switch?
21st Apr 2018, 2:22 PM
Timon Paßlick
+ 2
Sheldon Duncan Advanced coding is also with if and switch, no idea why they downvoted.
21st Apr 2018, 3:59 PM
Timon Paßlick
+ 1
Operator precedence is important. 4 + 5 * 10 = 54, and not 90
21st Apr 2018, 4:00 PM
Emma
0
I think the original poster is talking about parsing a mathematical expression, and then evaluating it. You normally use a tree for for this.
21st Apr 2018, 2:49 PM
Emma