Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Giving brackets precedence

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.

like image 485
hunterge Avatar asked Jan 01 '13 22:01

hunterge


People also ask

What is the precedence of brackets?

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.

Which operator has the highest order of precedence * () [] {}?

Explanation: Operator ++ has the highest precedence than / , * and +.

Which has the highest precedence () or?

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.

How parentheses can be used to change the precedence?

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.


1 Answers

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.

like image 98
Simon G. Avatar answered Oct 28 '22 18:10

Simon G.