Guest User

Untitled

a guest
Feb 19th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. package CS_240_Project_1;
  2. import java.util.*;
  3.  
  4. public class RPN implements REPL {
  5. ArrayStack<Integer> stack;
  6.  
  7. public RPN(){
  8. stack = new ArrayStack<Integer>();
  9. }
  10.  
  11. public String[] read() {
  12. Scanner sc = new Scanner(System.in);
  13. System.out.print("rpn> ");
  14. String ans = sc.next();
  15. StringTokenizer s = new StringTokenizer(ans);
  16.  
  17. int x = 0;
  18. String[] a = new String[30];
  19. while (s.hasMoreElements()) {
  20. a[x] = s.nextToken();
  21. x++;
  22. }
  23. return a;
  24. }
  25.  
  26. public void eval(String expr) throws StackUnderflowException {
  27. if (isInt(expr)) {
  28. int x = Integer.parseInt(expr);
  29. stack.push(x);
  30. }
  31. else if (expr == "+") {
  32. int x = stack.pop();
  33. int y = stack.pop();
  34. stack.push(x+y);
  35. }
  36. else if (expr == "*") {
  37. int x = stack.pop();
  38. int y = stack.pop();
  39. stack.push(x*y);
  40. }
  41. else if (expr == "-") {
  42. int x = stack.pop();
  43. int y = stack.pop();
  44. stack.push(y-x);
  45. }
  46. else if (expr == "/") {
  47. int x = stack.pop();
  48. int y = stack.pop();
  49. stack.push(y/x);
  50. }
  51.  
  52. else if (expr == "!") {
  53. while (!stack.isEmpty()) {
  54. stack.pop();
  55. }
  56. }
  57. else if (expr == ".") {
  58. System.out.println(stack.pop());
  59. }
  60. }
  61.  
  62. public void eval(String[] exprs) throws StackUnderflowException {
  63. for (int i = 0; i <= exprs.length; i++) {
  64. eval(exprs[i]);
  65. }
  66. }
  67.  
  68. public void print() throws StackUnderflowException {
  69. ArrayStack<Integer> stackCopy = stack;
  70. if (!stackCopy.isEmpty()) {
  71. System.out.println(stackCopy.pop());
  72. }
  73. }
  74.  
  75. public void loop() throws StackUnderflowException {
  76. while (true) {
  77. read();
  78. print();
  79. }
  80. }
  81.  
  82. public boolean isInt(String expr) {
  83. try { Integer.parseInt(expr);
  84. } catch (NumberFormatException E) {
  85. return false;
  86. }
  87. return true;
  88. }
  89. }
Add Comment
Please, Sign In to add comment