Stacks
This assignment is a postfix calculator. The idea is to to take a
postfix equation and output the result. To accomplish this you will
need a stack class, which you write your own.
Postfix Arithmetic
This is just some samples to illustrate what a valid postfix equation
looks like. The normal notation you typically use is actually "infix"
notation, this indicates that the operator is listed between the
operands. For "postfix" arithmetic, the operator is after the operands.
Here are some examples :
Infix Postfix
2 + 3 2 3 +
2 + 3 * 5 2 3 5 * +
(2 + 3) * 5 2 3 + 5 *
2 / 3 - 5 * 7 2 3 / 5 7 * -
The Stack class
Your stack will need to store doubles, and must have dynamic storage.
You may not use any library containers to accomplish this. It should
have a standard interface ( constructor, push, pop, peek, empty ).
Your pop and peek must throw exceptions if they are empty. As a
positive side effect when you get one of those exceptions it means that
the input was bad ( too many operators ). And this case should be
checked for.
The Postfix Calculator
Here is the logic:
- If the input is a number push it onto the stack.
- If the input is an operator, pop top two numbers and apply the
operator.
Note: The first number off the stack is the right hand side of
the operation. The result is then pushed on the stack.
For this calculator we need to support + - / * ^.
Note: the exponentiation operation (^) can't be executed with that operator,
you will need Math.pow for that.
This needs to have the following features.
- Input postfix expressions may span lines.
- It must read until end of file. ( eof is control-d )
- The ability to deal with multi-digit integers as input.
- It must support these operators + - * / ^
- generate the result as a floating point ( double ).
NOTE: If done correctly there will be a lot of exception handling in
this code.
Here are some sample runs from mine
This is due on July 14th.
useful Java API calls
- Math.pow
- Double.parseDouble
- String.contains
The Goals
- write and use a stack
- solve a simple stack problem