//Sorry I didnt include the code, it is to be coded in Java as well. I was unabl
ID: 3861728 • Letter: #
Question
//Sorry I didnt include the code, it is to be coded in Java as well. I was unable to find the proper postfix method in my book.
import java.util.*;
public class InfixToPostfixParens {
private static final String OPERATORS = "-+*/()";
private static final int[] PRECEDENCE = {1, 1, 2, 2, -1, -1};
private static final String PATTERN = "\d+\.\d*|\d+|" + "\p{L}[\p{L}\p{N}]*" + "|[" + OPERATORS + "]";
private final Deque<Character> operatorStack = new ArrayDeque<>();
private final StringJoiner postfix = new StringJoiner(" ");
public static String convert(String infix) throws SyntaxErrorException {
InfixToPostfixParens infixToPostfixParens = new InfixToPostfixParens();
infixToPostfixParens.convertToPostfix(infix);
return infixToPostfixParens.getPostfix();
}
private String getPostfix() {
return postfix.toString(); }
private void convertToPostfix(String infix) throws SyntaxErrorException {
try { String nextToken; Scanner scan = new Scanner(infix);
while ((nextToken = scan.findInLine(pattern)) != null)
{ char firstChar = nextToken.charAt(0);
if (Character.isLetter(firstChar) || Character.isDigit(firstChar))
{ postfix.add(nextToken); }
else if(isOperator(firstChar)) {
processOperator(firstChar); }
else { throw new SyntaxErrorException ("Unexpected Character Encountered: " + firstChar); } }
while (!operatorStack.isEmpty()) {
char op = operatorStack.pop();
if (op == '(') throw new SyntaxErrorException ("Unmatched opening parenthesis");
postfix.add(new Character(op).toString());
}
return postfix.toString(); }
catch (NoSuchElementException ex) {
throw new SyntaxErrorException("Syntax Error: The stack is empty");
}
}
private void processOperator(char op) {
if (operatorStack.isEmpty() || op == '(')
{ operatorStack.push(op);
} else {
char topOp = operatorStack.peek();
if (precedence(op) > precedence(topOp)) {
operatorStack.push(op);
}
else {
while (!operatorStack.isEmpty() && precedence(op) <= precedence(topOp)) {
operatorStack.pop();
if (topOp == '(') {
break; }
postfix.add(new Character(topOp).toString());
if (!operatorStack.isEmpty()) { // Reset topOp.
topOp = operatorStack.peek(); } }
// assert: Operator stack is empty or // current operator precedence > // top of stack operator precedence.
if (op != ')') operatorStack.push(op);
}
}
}
public static class SyntaxErrorException extends Exception {
SyntaxErrorException(String message) {
super(message); }
}
private static boolean isOperator(char ch) {
return OPERATORS.indexOf(ch) != -1;
}
private static int precedence(char op) {
return PRECEDENCE[OPERATORS.indexOf(op)] ;
}
}
Explanation / Answer
package postfix;
import java.util.*;
public class InfixToPostfixParens {
private static final String OPERATORS = "-+*/()";
private static final int[] PRECEDENCE = { 1, 1, 2, 2, -1, -1 };
private static final String PATTERN = "\d+\.\d*|\d+|" + "\p{L}[\p{L}\p{N}]*" + "|[" + OPERATORS + "]";
private final Deque<Character> operatorStack = new ArrayDeque<>();
private final StringJoiner postfix = new StringJoiner(" ");
private int alphaCount = 0;
private int operatorCount = 0;
public static String convert(String infix) throws SyntaxErrorException {
InfixToPostfixParens infixToPostfixParens = new InfixToPostfixParens();
infixToPostfixParens.convertToPostfix(infix);
return infixToPostfixParens.getPostfix();
}
private String getPostfix() {
return postfix.toString();
}
private String convertToPostfix(String infix) throws SyntaxErrorException {
try {
alphaCount = 0;
operatorCount = 0;
String nextToken;
Scanner scan = new Scanner(infix);
while ((nextToken = scan.findInLine(PATTERN)) != null) {
char firstChar = nextToken.charAt(0);
if (Character.isLetter(firstChar) || Character.isDigit(firstChar)) {
postfix.add(nextToken);
alphaCount++;
}
else if (isOperator(firstChar)) {
if(firstChar == '+' || firstChar == '-' || firstChar == '*' || firstChar == '/' ){
operatorCount++;
}
processOperator(firstChar);
} else {
throw new SyntaxErrorException("Unexpected Character Encountered: " + firstChar);
}
}
char op = ' ';
if(alphaCount<=operatorCount){
throw new SyntaxErrorException("Missing operator");
}
while (!operatorStack.isEmpty()) {
op = operatorStack.pop();
if (op == '('){
throw new SyntaxErrorException("Unmatched opening parenthesis");
}
postfix.add(new Character(op).toString());
}
return postfix.toString();
} catch (NoSuchElementException ex) {
throw new SyntaxErrorException("Syntax Error: The stack is empty");
}
}
private void processOperator(char op) {
if (operatorStack.isEmpty() || op == '(') {
operatorStack.push(op);
} else {
char topOp = operatorStack.peek();
if (precedence(op) > precedence(topOp)) {
operatorStack.push(op);
} else {
while (!operatorStack.isEmpty() && precedence(op) <= precedence(topOp)) {
operatorStack.pop();
if (topOp == '(') {
break;
}
postfix.add(new Character(topOp).toString());
if (!operatorStack.isEmpty()) { // Reset topOp.
topOp = operatorStack.peek();
}
}
// assert: Operator stack is empty or // current operator
// precedence > // top of stack operator precedence.
if (op != ')')
operatorStack.push(op);
}
}
}
public static class SyntaxErrorException extends Exception {
SyntaxErrorException(String message) {
super(message);
}
}
private static boolean isOperator(char ch) {
return OPERATORS.indexOf(ch) != -1;
}
private static int precedence(char op) {
return PRECEDENCE[OPERATORS.indexOf(op)];
}
}
package postfix;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import postfix.InfixToPostfixParens.SyntaxErrorException;
public class GeneratePostfix {
public static void main(String args[]) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true){
System.out.println("Enter the infix expression(Enter -1 to exit:");
try {
String input = br.readLine();
if(input.equals("-1")) break;
System.out.println(InfixToPostfixParens.convert(input));
} catch (SyntaxErrorException | IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
}
Output:
Enter the infix expression(Enter -1 to exit:
(a+b)*c
a b + c *
Enter the infix expression(Enter -1 to exit:
(a+b*c
Unmatched opening parenthesis
Enter the infix expression(Enter -1 to exit:
a++b
Missing operator
Enter the infix expression(Enter -1 to exit:
a+
Missing operator
Enter the infix expression(Enter -1 to exit:
ab+
Missing operator
Enter the infix expression(Enter -1 to exit:
-1
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.