Guest User

Untitled

a guest
May 23rd, 2018
166
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.util.ArrayDeque;
  2. import java.util.Scanner;
  3.  
  4. /**
  5. * Created by IntelliJ IDEA.
  6. * User: LAPD
  7. * Date: 22.5.2018 г.
  8. * Time: 08:59 ч.
  9. */
  10. public class _15InfixToPostfix {
  11. public static void main(String[] args) {
  12. Scanner console = new Scanner(System.in);
  13.  
  14. String[] input = console.nextLine()
  15. .split("\\s+");
  16.  
  17. ArrayDeque<String> operatorStack = new ArrayDeque<>();
  18. StringBuilder output = new StringBuilder();
  19.  
  20. for (int i = 0; i < input.length; i++) {
  21. String currentToken = input[i];
  22.  
  23. if (currentToken.matches("\\d+")) {
  24. output.append(currentToken)
  25. .append(" ");
  26. } else if (currentToken.matches("[a-z]+")) {
  27. operatorStack.push(currentToken);
  28. } else if (currentToken.matches("[+\\-*/]")) {
  29.  
  30. String stackTopOperator;
  31. while (!operatorStack.isEmpty()
  32. && ((stackTopOperator = operatorStack.peek()).matches("[a-z]+")
  33. || hasGreaterPrecedenceOrEqualAndLeft(currentToken, stackTopOperator))
  34. && !"(".equals(stackTopOperator)) {
  35.  
  36. output.append(operatorStack.pop())
  37. .append(" ");
  38. }
  39.  
  40. operatorStack.push(currentToken);
  41. } else if ("(".equals(currentToken)) {
  42. operatorStack.push(currentToken);
  43. } else if (")".equals(currentToken)) {
  44.  
  45. String stackTopOperator;
  46.  
  47. while (!"(".equals(stackTopOperator = operatorStack.peek())) {
  48. output.append(operatorStack.pop())
  49. .append(" ");
  50. }
  51.  
  52. operatorStack.pop();
  53. }
  54. }
  55.  
  56. while (!operatorStack.isEmpty()) {
  57. output.append(operatorStack.pop())
  58. .append(" ");
  59. }
  60.  
  61. output.setLength(output.length() - 1);
  62. System.out.println(output);
  63. }
  64.  
  65. private static boolean hasGreaterPrecedenceOrEqualAndLeft(String currentToken, String peek) {
  66.  
  67. if (currentToken.equals(peek)) {
  68. return true;
  69. }
  70.  
  71. switch (currentToken) {
  72. case "+":
  73. case "-":
  74. return true;
  75. case "*":
  76. return "/".equals(peek);
  77. case "/":
  78. return "*".equals(peek);
  79. case "(":
  80. return true;
  81. default:
  82. return false;
  83. }
  84. }
  85. }
RAW Paste Data