Advertisement
Guest User

Untitled

a guest
May 21st, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1.  
  2. import java.util.Stack;
  3. public class PostFixCalculator {
  4.  
  5.  
  6. public Stack push;
  7. public static void main(String[] args) {
  8.  
  9.  
  10. String postfix = In.readLine();
  11.  
  12. In.close();
  13.  
  14. System.out.println(postfix);
  15. }
  16.  
  17. public static int evalPostfix(String postfix) {
  18.  
  19. Stack valStack = new Stack();
  20.  
  21. while (In.done()) {
  22. String token = In.readIdentifier();
  23. char c = token.charAt(0);
  24. if (Character.isDigit(c)) {
  25. valStack.push(new Integer(token));
  26. }
  27. else {
  28. int firstValue = ((Integer)valStack.pop()).intValue();
  29. int secondValue = ((Integer)valStack.pop()).intValue();
  30. int resultValue;
  31.  
  32. switch (c) {
  33. case '+':
  34. resultValue = firstValue + secondValue;
  35. break;
  36. case '-':
  37. resultValue = firstValue - secondValue;
  38. break;
  39. case '*':
  40. resultValue = firstValue * secondValue;
  41. break;
  42. case '/':
  43. resultValue = firstValue / secondValue;
  44. break;
  45.  
  46. default:
  47. throw new IllegalArgumentException("invalid postfix expression");
  48. }
  49.  
  50. valStack.push(new Integer(resultValue));
  51. }
  52. }
  53.  
  54. int resultValue = ((Integer)valStack.pop()).intValue();
  55. if (!valStack.empty()) {
  56. throw new IllegalArgumentException("invalid postfix expression");
  57. }
  58.  
  59. return resultValue;
  60. }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement