Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Stack;
- public class PostFixCalculator {
- public Stack push;
- public static void main(String[] args) {
- String postfix = In.readLine();
- In.close();
- System.out.println(postfix);
- }
- public static int evalPostfix(String postfix) {
- Stack valStack = new Stack();
- while (In.done()) {
- String token = In.readIdentifier();
- char c = token.charAt(0);
- if (Character.isDigit(c)) {
- valStack.push(new Integer(token));
- }
- else {
- int firstValue = ((Integer)valStack.pop()).intValue();
- int secondValue = ((Integer)valStack.pop()).intValue();
- int resultValue;
- switch (c) {
- case '+':
- resultValue = firstValue + secondValue;
- break;
- case '-':
- resultValue = firstValue - secondValue;
- break;
- case '*':
- resultValue = firstValue * secondValue;
- break;
- case '/':
- resultValue = firstValue / secondValue;
- break;
- default:
- throw new IllegalArgumentException("invalid postfix expression");
- }
- valStack.push(new Integer(resultValue));
- }
- }
- int resultValue = ((Integer)valStack.pop()).intValue();
- if (!valStack.empty()) {
- throw new IllegalArgumentException("invalid postfix expression");
- }
- return resultValue;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement