Advertisement
vaakata

Ex12_InfixToPostfix_25Jan2017

Jan 25th, 2017
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.24 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class Ex12_InfixToPostfix_25Jan2017 {
  4.     public static void main(String[] args) {
  5.         Locale.setDefault(Locale.ROOT);
  6.  
  7.         Scanner sc = new Scanner(System.in);
  8.  
  9.         String[] input = sc.nextLine().split("\\s+");
  10.         Deque<String> numbersQueue = new ArrayDeque<>();
  11.         Deque<String> operatorStack = new ArrayDeque<>();
  12.  
  13.  
  14.         for (String s : input) {
  15.             if(Character.isDigit(s.charAt(0)) || Character.isLetter(s.charAt(0))) {
  16.                 numbersQueue.offer(s);
  17.             } else {
  18.                 String lastOperator = operatorStack.peek();
  19.                 try {
  20.                     if (s.equals("+") || s.equals("-")) {
  21.                         if (lastOperator.equals("+") || lastOperator.equals("-")) {
  22.                             numbersQueue.offer(operatorStack.pop());
  23.                             operatorStack.push(s);
  24.                         } else {
  25.                             operatorStack.push(s);
  26.                         }
  27.                     } else if (s.equals("*") || s.equals("/")) {
  28.                         if (lastOperator.equals("*") || lastOperator.equals("/")) {
  29.                             numbersQueue.offer(operatorStack.pop());
  30.                             operatorStack.push(s);
  31.                         } else {
  32.                             operatorStack.push(s);
  33.                         }
  34.                     } else if (s.equals("(")) {
  35.                         operatorStack.push(s);
  36.                     } else if (s.equals(")")) {
  37.                         while (!operatorStack.peek().equals("(")) {
  38.                             numbersQueue.offer(operatorStack.pop());
  39.                         }
  40.                         //Removing the non-necessary open parenthesis '('
  41.                         operatorStack.pop();
  42.                     } else {
  43.  
  44.                     }
  45.                 } catch (Exception ex){
  46.                     operatorStack.push(s);
  47.                 }
  48.             }
  49.         }
  50.  
  51.         while (!numbersQueue.isEmpty()){
  52.             System.out.print(numbersQueue.poll() + " ");
  53.         }
  54.  
  55.         while (!operatorStack.isEmpty()){
  56.             System.out.print(operatorStack.pop() + " ");
  57.         }
  58.         System.out.println();
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement