Question
In java, mport java.util.ArrayDeque; import java.util.Deque; import java.util.EmptyStackException; import java.util.regex.Pattern; import java.util.Scanner; import java.util.StringJoiner; /** Translates an infix expression with parentheses * to a postfix
In java,
mport java.util.ArrayDeque; import java.util.Deque; import java.util.EmptyStackException; import java.util.regex.Pattern; import java.util.Scanner; import java.util.StringJoiner;
/** Translates an infix expression with parentheses * to a postfix expression. * @author Koffman & Wolfgang */ public class InfixToPostfixParens2 { private InfixToPostfixParens2() {}
// Nested Class /** Class to report a syntax error. */ public static class SyntaxErrorException extends Exception {
/** * Construct a SyntaxErrorException with the specified * message. * @param message The message */ SyntaxErrorException(String message) { super(message); } } // Data Fields /** The operators */ private static final String OPERATORS = "-+*/()"; /** * The Pattern to extract tokens * A token is either a string of digits (\d+) * or a JavaIdentifier * or an operator */ private static final String PATTERN = "\\d+\\.\\d*|\\d+|\\p{L}[\\p{L}\\p{N}]*|[" + OPERATORS + "]"; /** The precedence of the operators, matches order of OPERATORS. */ private static final int[] PRECEDENCE = {1, 1, 2, 2, -1, -1}; /** The postfix string */
/** * Convert a string from infix to postfix. * @param infix The infix expression * @throws SyntaxErrorException */ public static String convert(String infix) throws SyntaxErrorException { Deque
/** * Method to process operators. * @param op The operator * @throws EmptyStackException */ private static void processOperator(char op, Deque // assert: Operator stack is empty or // current operator precedence > // top of stack operator precedence. if (op != ')') { operatorStack.push(op); } } } } /** * Determine whether a character is an operator. * @param ch The character to be tested * @return true if ch is an operator */ private static boolean isOperator(char ch) { return OPERATORS.indexOf(ch) != -1; } /** * Determine the precedence of an operator. * @param op The operator * @return the precedence */ private static int precedence(char op) { return PRECEDENCE[OPERATORS.indexOf(op)]; } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started