Tuesday, September 25, 2007

Calculator How-To Using Java 2 Part 2

Today, I shall continue with the guide on Calculation How-To. In the previous part, we have discussed about the 4 fundamental steps to create this little calculator program.

Instead of scratching on the surface, I will go a bit deeper into the topic this time. I will not touch on the first 3 steps as I feel that it shouldn't be at your wits' end. Easy as pie I suppose! I will dive straight into the Step 4 and give you quite a handful of additional information that you will need in your development.


How a real calculator works (Implementation of Stack) - The Program Design

I will be using 2 Stacks here. The first Stack is used to convert an infix expression to a postfix expression.

Well, an infix expression is something like 5 + 2 where the operator is in the center. Infix is the most commonly used expression taught in school. However, a postfix is something special. The operator is at the back. It is used by computers to evaluate results from certain expression.

Illustration of conversion between the infix and the postfix expression below:

An algorithm has to be used for this kind of conversion. You can check out one of the algorithms here.

The second Stack is the real stuff that does the computation.


As i have mentioned previously, the whole expression is read by your program. One by one, the digits are stored into the Stack. However whenever an operator ( be it +, -, *, or / in the expression) is encountered, the program will pop the last two values out and evaluate them and then push the result back into the stack. Likewise, the program will complete all the operators and pop out the last value in the Stack as final result.

Here comes to the end of Part II. I hope that my guide comes in handy to you. :)

Posted by Zack at 8:19 PM