Advertisement
Guest User

Untitled

a guest
Feb 20th, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.util.Stack;
  3.  
  4. public class PostfixCalculator {
  5. private final static char ADD = '+';
  6. private final static char SUBTRACT = '-';
  7. private final static char MULTIPLY = '*';
  8. private final static char DIVIDE = '/';
  9. private Stack<Integer> stack;
  10.  
  11. public PostfixCalculator() {
  12. stack = new Stack<Integer>();
  13. }
  14.  
  15. public int evaluate(String expr) {
  16.  
  17. int op1, op2, result = 0;
  18. String token;
  19. Scanner parser = new Scanner(expr);
  20. while (parser.hasNext()) {
  21. token = parser.next();
  22. if (isOperator(token)) {
  23. op2 = (stack.pop()).intValue();
  24. op1 = (stack.pop()).intValue();
  25. result = evaluateSingleOperator(token.charAt(0), op1, op2);
  26. stack.push(new Integer(result));
  27. } else
  28. stack.push(new Integer(Integer.parseInt(token)));
  29. }
  30. return result;
  31. }
  32.  
  33. private boolean isOperator(String token) {
  34. return (token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/"));
  35. }
  36.  
  37. private int evaluateSingleOperator(char operation, int op1, int op2) {
  38. int result = 0;
  39. switch (operation) {
  40. case ADD:
  41. result = op1 + op2;
  42. break;
  43. case SUBTRACT:
  44. result = op1 - op2;
  45. break;
  46. case MULTIPLY:
  47. result = op1 * op2;
  48. break;
  49. case DIVIDE:
  50. result = op1 / op2;
  51.  
  52. }
  53. return result;
  54. }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement