Guest User

Untitled

a guest
Jan 15th, 2020
76
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public double getResult(Queue<String> queue)
  2. {
  3. Stack<Double> stack = new Stack<>();
  4. String next = queue.remove();
  5. double temp = 0;
  6. while(queue.size() >= 0)
  7. {
  8. switch (next)
  9. {
  10. case "+":
  11. {
  12. double a = stack.pop(), b = stack.pop();
  13. temp = a + b;
  14. stack.push(temp);
  15. break;
  16. }
  17. case "-":
  18. {
  19. double a = stack.pop(), b = stack.pop();
  20. temp = b - a;
  21. stack.push(temp);
  22. break;
  23. }
  24. case "*":
  25. {
  26. double a = stack.pop(), b = stack.pop();
  27. temp = a * b;
  28. stack.push(temp);
  29. break;
  30. }
  31. case "^":
  32. {
  33. double a = stack.pop(), b = stack.pop();
  34. temp = Math.pow(b, a);
  35. stack.push(temp);
  36. break;
  37. }
  38. case "/":
  39. {
  40. double a = stack.pop(), b = stack.pop();
  41. temp = b / a;
  42. stack.push(temp);
  43. break;
  44. }
  45. case "!":
  46. {
  47. long a = (long)(stack.pop()).doubleValue();
  48. if (a >= 16)
  49. a++;
  50. else
  51. {
  52. long t = 1;
  53. for (int i = 1; i <= a; i++)
  54. t *= i;
  55. stack.push((double)t);
  56. }
  57. break;
  58. }
  59. case "sin":
  60. {
  61. double a = stack.pop();
  62. temp = Math.sin(a);
  63. stack.push(temp);
  64. break;
  65. }
  66. case "cos":
  67. {
  68. double a = stack.pop();
  69. temp = Math.cos(a);
  70. stack.push(temp);
  71. break;
  72. }
  73. case "tan": {
  74. double a = stack.pop();
  75. temp = Math.tan(a);
  76. stack.push(temp);
  77. break;
  78. }
  79. case "sqrt":
  80. {
  81. double a = stack.pop();
  82. temp = Math.sqrt(a);
  83. stack.push(temp);
  84. break;
  85. }
  86. case "ln":
  87. {
  88. double a = stack.pop();
  89. temp = Math.log(a);
  90. stack.push(temp);
  91. break;
  92. }
  93. case "log":
  94. {
  95. double a = stack.pop();
  96. temp = Math.log10(a);
  97. stack.push(temp);
  98. break;
  99. }
  100. case "abs":
  101. {
  102. double a = stack.pop();
  103. temp = Math.abs(a);
  104. stack.push(temp);
  105. break;
  106. }
  107. case "m":
  108. {
  109. stack.push(-stack.pop());
  110. break;
  111. }
  112. default:
  113. {
  114. stack.push(Double.parseDouble(next));
  115. break;
  116. }
  117. }
  118. if (queue.size() == 0)
  119. return stack.pop();
  120. else
  121. next = queue.remove();
  122. }
  123. try {
  124. if (stack.size() > 0)
  125. throw new Exception("Аператары і аперанды не супадаюць");
  126. }
  127. catch (Exception ex) { }
  128. return temp;
  129. }
RAW Paste Data