I'm very new to java and I'm building a calculator, that takes an equation and evaluates it.
I'm using the Scanner method to get an input, but this means my input is a Scanner type. What should I do to this input so I can evaluate it? And once I can evaluate it, how can i give precedence to brackets?
For example, for the equation (5*(4+3))*2 , I'd like the program to evaluate (4+3) first, then have it multiplied by 4, then all of that multiplied by 2.
Thanks a lot.
Expression evaluation is from left to right; parentheses and operator precedence modify this: When parentheses are encountered (other than those that identify function calls) the entire subexpression between the parentheses is evaluated immediately when the term is required.
Explanation: Operator ++ has the highest precedence than / , * and +.
The operator precedence is responsible for evaluating the expressions. In Java, parentheses() and Array subscript[] have the highest precedence in Java. For example, Addition and Subtraction have higher precedence than the Left shift and Right shift operators.
For example, 1 + 2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is treated as (1 * 2) + 3 because the multiplication operator has a higher precedence than the addition operator. You can use parentheses to override the default operator precedence rules.
What you need is Dijkstra's Shunting Yard Algorithm. This converts in-fix mathematical notation into post-fix notation, which neatly sorts out all problems with operator precedence and brackets as post-fix notation has no need for either of them. The Wikipedia page has a full example in C, which could be translated into Java.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With