Guest User

Untitled

a guest
Jul 16th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. /******************************************************************************
  2. * Compilation: javac Evaluate.java
  3. * Execution: java Evaluate
  4. * Dependencies: Stack.java
  5. *
  6. * Evaluates (fully parenthesized) arithmetic expressions using
  7. * Dijkstra's two-stack algorithm.
  8. *
  9. * % java Evaluate
  10. * ( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) )
  11. * 101.0
  12. *
  13. * % java Evaulate
  14. * ( ( 1 + sqrt ( 5 ) ) / 2.0 )
  15. * 1.618033988749895
  16. *
  17. *
  18. *
  19. * Remarkably, Dijkstra's algorithm computes the same
  20. * answer if we put each operator *after* its two operands
  21. * instead of *between* them.
  22. *
  23. * % java Evaluate
  24. * ( 1 ( ( 2 3 + ) ( 4 5 * ) * ) + )
  25. * 101.0
  26. *
  27. * Moreover, in such expressions, all parentheses are redundant!
  28. * Removing them yields an expression known as a postfix expression.
  29. * 1 2 3 + 4 5 * * +
  30. *
  31. *
  32. ******************************************************************************/
  33.  
  34. public class Evaluate {
  35. public static void main(String[] args) {
  36. Stack<String> ops = new Stack<String>();
  37. Stack<Double> vals = new Stack<Double>();
  38.  
  39. while (!StdIn.isEmpty()) {
  40. String s = StdIn.readString();
  41. if (s.equals("(")) ;
  42. else if (s.equals("+")) ops.push(s);
  43. else if (s.equals("-")) ops.push(s);
  44. else if (s.equals("*")) ops.push(s);
  45. else if (s.equals("/")) ops.push(s);
  46. else if (s.equals("sqrt")) ops.push(s);
  47. else if (s.equals(")")) {
  48. String op = ops.pop();
  49. double v = vals.pop();
  50. if (op.equals("+")) v = vals.pop() + v;
  51. else if (op.equals("-")) v = vals.pop() - v;
  52. else if (op.equals("*")) v = vals.pop() * v;
  53. else if (op.equals("/")) v = vals.pop() / v;
  54. else if (op.equals("sqrt")) v = Math.sqrt(v);
  55. vals.push(v);
  56. }
  57. else vals.push(Double.parseDouble(s));
  58. }
  59. StdOut.println(vals.pop());
  60. }
  61. }
Add Comment
Please, Sign In to add comment