Hello People,
I am trying to create a java program that inputs an infix expression, then gives the output in postfix and prefix. So far the code compiled without errors but the answers for the postfix and prefix are not coming out correctly. Also the outputs come out wrong when i put parenthesis.
This is the code, pls help.
import java.io.*;
import java.util.*;
public class InToPosToPre{
private static Stack<Character> operatorStack = new Stack<Character> ();
private static Stack<Comparable> operandStack = new Stack<Comparable> ();
private static String toPostfix(String infix){
StringTokenizer s = new StringTokenizer(infix);
String symbol, postfix = "";
while (s.hasMoreTokens()){
symbol = s.nextToken();
if (Character.isDigit(symbol.charAt(0))){
postfix = postfix + " " + (Integer.parseInt(symbol));
}else if (symbol.equals("(")){
Character operator = new Character('(');
operatorStack.push(operator);
}else if (symbol.equals(")")){
while (operatorStack.peek().charValue() != '('){
postfix = postfix + " " + operatorStack.pop();
}
operatorStack.pop();
}else{
while (!operatorStack.empty() && !(operatorStack.peek()).equals("(") && prec(symbol.charAt(0)) <= prec(operatorStack.peek().charValue()))
postfix = postfix + " " + operatorStack.pop();
Character operator = new Character(symbol.charAt(0));
operatorStack.push(operator);
}}
while (!operatorStack.empty())
postfix = postfix + " " + operatorStack.pop();
return postfix;
}
private static String toPrefix(String infix){
StringTokenizer pre = new StringTokenizer(infix);
String symbol1 , prefix= "";
while(pre.hasMoreTokens()){
symbol1 = pre.nextToken();
if(Character.isDigit(symbol1.charAt(0))){
prefix = prefix+ " " +(Integer.parseInt(symbol1));
}else if(symbol1.equals("(")){
Character operand = new Character('(');
operandStack.push(operand);
}else if(symbol1.equals(")")){
while (((Character)operandStack.peek()).charValue()!= '('){
prefix = prefix + " " + operandStack.pop();
}
operandStack.pop();
}else{
while(!operandStack.empty()&&!(operandStack.peek()).equals("(")
&& prec(symbol1.charAt(0))<= prec(((Character)operandStack.peek()).charValue()))
prefix = prefix + " "+ operandStack.pop();
Character operand = new Character(symbol1.charAt(0));
operandStack.push(operand);
}}
while(!operandStack.empty())
prefix = prefix + " " +operandStack.pop();
return prefix;
}
private static int prec(char x){
if (x == '+' || x == '-'){
return 1;
}
else if (x=='^' && x == '*' || x == '/' || x == '%'){
return 2;
}
else{
return 0;
}
}
public static void main(String args[]) throws IOException{
BufferedReader keyboard = new BufferedReader (new InputStreamReader(System.in));
String infix;
System.out.print("Input a infix: ");
infix = keyboard.readLine();
System.out.println("Expression in postfix:" + toPostfix(infix));
System.out.println("Expression in prefix: " + toPrefix(infix));
}
}