Skip to content
Advertisement

Prefix To Postfix Java

I need some help with my prefix to postfix code. When ever I generate the action through GUI from the expression “* 2 + 2 – + 12 9 2” it returns 2*. It should be returning “2 2 12 9 + 2 -+*”. I keep changing the code around and I keep ending up with the same result. Please I would appreciate any guidance.

import java.util.*; 

public class Postfix{ 
      
    static String prePostfix(String p){ 
      
        Stack<String> stack = new Stack<String>(); 
      
        int l = p.length(); 
      
        for(int i = l-1; i >= 0; i--){ 
            if(isOperator(p.charAt(i))){ 
      
                String stack1 = stack.peek(); 
                stack.pop();
                String stack2 = stack.peek(); 
                stack.pop(); 
      
                String temp = stack1 + stack2 + p.charAt(i); 
      
                stack.push(temp); 
            } 
      
            else{ 
                stack.push(p.charAt(i) + ""); 
            } 
        } 
      
        return stack.peek(); 
    } 
    
    static boolean isOperator(char x){ 
        switch (x){ 
            case '+':
            case '-': 
            case '/': 
            case '*':
            case '^':
                return true; 
        } 
        return false; 
    } 
}

Advertisement

Answer

your problem is you don’t consider the delimiters you have in your expression, which are the spaces between each sub expressions.

I suggest for you not working on the original string with the delimiters, just split your string to the arguments and work on that array, and join them later with your preferred delimiter.

anyway, here is the fixed code:

import java.util.*; 

public class Postfix{ 
  
static String prePostfix(String p){ 
  
    Stack<String> stack = new Stack<String>(); 
    String[] arrOfStr = p.split(" ");
    int l = arrOfStr.length; 
    for(int i = l-1; i >= 0; i--){ 
        if(isOperator(arrOfStr[i].charAt(0))){ 
  
            String stack1 = stack.peek(); 
            stack.pop();
            String stack2 = stack.peek(); 
            stack.pop(); 
  
            String temp = stack1 + " " + stack2 + " " + arrOfStr[i]; 
  
            stack.push(temp); 
        } 
        else{ 
            stack.push(arrOfStr[i]); 
        } 
    } 
  
    return stack.peek(); 
} 

static boolean isOperator(char x){ 
    switch (x){ 
        case '+':
        case '-': 
        case '/': 
        case '*':
        case '^':
            return true; 
    } 
    return false; 
} 

}

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement