import java.util.StringTokenizer; import java.util.Scanner; import java.util.Stack; /** Convert.java -- convert infix to postfix. To finish in lab. */ public class Convert { public static void main(String [] args) throws IOException { Scanner kbd = new Scanner(System.in); System.out.print("Please enter an infix expression: "); String line = kbd.nextLine(); System.out.println("You entered " + line); StringTokenizer tok = new StringTokenizer(line, " "); Stack stack = new Stack(); String postfix = ""; while (tok.hasMoreTokens()) { String token = tok.nextToken(); // Now we handle various cases depending on what the token is. // Case 1: If the token is an operand, append it to the postfix // expression. This is because the order of the operands doesn't change, // and the operators will be appended later. It will suffice to look at // the first character to see if it is a digit or a decimal point. // Case 2: We should always push open parentheses // Case 3: When we encounter a ')', we need to pop operators off the // stack until we see the corresponding '('. The operators will then be // in the appropriate order in the postfix output. But we need to avoid // putting the '(' in the postfix output. // Case 4: The last case handles all the operators, + - * / // If the stack is empty, push this operand on the stack. // If the stack is not empty, pop operators of >= precedence for output, // stopping when we encounter a '(' or an operator of lower precedence, // or the stack becomes empty. Finally, push this operator on stack. // (For an operator of equal precedence we should pop because of // left-to-right associativity.) } // When we run out of input, don't forget to empty (pop) the stack // onto the output. System.out.println("The postfix version of the expression is " + postfix); } // A method to determine if one operator is of lower precedence. // The only case where we return true is when the first operand is strictly // lower precedence, which encompasses the cases of op1 = + or - and // op2 = * or /. public static boolean lowerPrecedence(char op1, char op2) { if ((op1 == '+' || op1 == '-') && (op2 == '*' || op2 == '/')) return true; else return false; } }