-2

Can anyone here guide me about this problem. I am new in Java and our professor gave us a Laboratory Exercise called "Scientific Calculator".

This program will solve this kind of expressions: 1. 6+(4*6) 2. ((50+25)/5)+12 3. 15/3*3

i have a code here but it will just add the following expressions. If the user input another expression like :

(79+34)-5 or any...

My program will go crazy.

He told us that we can use Stack or Arrays but my problem is i don't have any idea where and what to start. Thanks!

UPDATE: I found the answer

Null
  • 73
  • 1
  • 15

2 Answers2

0

I guess your professor would love to see you learning the Shunting-yard algorithm from this assignment. Some good explanation can be seen from the posts Explanation on Shunting-yard algorithm, Look for Detailed example from Wiki. I guess getting the concept right is a good place to start with. It is fun if you can complete the assignment by yourself.

Community
  • 1
  • 1
bLaXjack
  • 780
  • 2
  • 11
  • 23
0

You need to remember the order of operations - BODMAS (brackets, of (powers), division, multiplication, addition, subtraction) and solve in that order.

you can use stacks implicitly by using recursion, but you need to have a sound exit strategy for that to work out well. do the operations you find, until you get an opening bracket, locate the closing bracket, and send the contents of that to the same function, return when you have no more tokens to parse.

pseudo code:

int recursivefunc(String expression){
    result = 0;
 while (have token){
   if token is add/subtract/divide -{
     result = result + "token operation result"
    }else if token is open bracket{
      find end bracket (not the first if there are more open brackets)
       result = result + recursivefunc(sub-expression)
    }
  }
  return result
}
JoSSte
  • 2,953
  • 6
  • 34
  • 54