Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Description of program: You are to write a program name InfixToPostfix.java that

ID: 3597728 • Letter: D

Question

Description of program: You are to write a program name InfixToPostfix.java that converts an infix expression entered by the user to a postfix expression. The expression may contain the following tokens: (1) Integer constants (a series of decimal digits). 2) x (representing a value to be supplied later) (3) Binary operators (+,-,*,/and %). 4) Parentheses Spaces between tokens are allowed but not required. The program will convert the expression to postfix form and display the converted expression. Enter infix expression: (x+1) * (x-2)/4 Converted expression: x 1+x 2-*4/ Enter infix expression: 12+ Error in expression!! No operator between operands. Also last token must be an operand. Enter infix expression: 10.4 Error in expression!! Cannot accept floating point numbers Enter infix expression: 1 (2) Error in expression!! No operator between operand and left parentheses. Enter infix expression: 5- (x- 2)) Error in expression!! No matching left parentheses for a right parentheses Enter infix expression: 1** 2 Error in expression!! The* operator cannot be preceded by a * operator.

Explanation / Answer

public class InfixToPostfix { private static boolean isOperator(char c) { return c == '+' || c == '-' || c == '*' || c == '/' || c == '^' || c == '(' || c == ')'; } private static boolean isLowerPrecedence(char op1, char op2) { switch (op1) { case '+': case '-': return !(op2 == '+' || op2 == '-'); case '*': case '/': return op2 == '^' || op2 == '('; case '^': return op2 == '('; case '(': return true; default: return false; } } public static String convertToPostfix(String infix) { Stack stack = new Stack(); StringBuffer postfix = new StringBuffer(infix.length()); char c; for (int i = 0; i