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

//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)] ;
       }


  
      
   }


      

  
  

Consider the infix-postfix conversion algorithm given in your textbook (pages 174-176). Implement the algorithm but do not assume the infix expressions are error free. For each infix expression (your program must handle any number of them) convert and display the correct postfix equivalent. If the infix expression is syntactically incorrect display a message which indicates the type of error. Your program must place the postfix expression into a queue and when conversion is complete display the queue. The algorithm in the book uses a String for the postfix expression, you must use a queue. Operands are single character identifiers. Consider the binary operators of +, -, * and/, with normal operator precedence, parentheses are used to change normal precedence rules. Expressions may contain blanks (any number of them) as delimiters. Your error checking must be incorporated into the translation algorithm given in the book; it cannot be handled in a separate pre-translation pass of the expression. You should be able to recognize at least the following three errors; mismatched parentheses, missing operand, and missing operator. You are to use exceptions as the method of alerting of the error, and must raise a different exception for each of the three errors. A sample run might be: (a + b)*c rightarrow ab + c* (a + b * c rightarrow mismatched parentheses a + + b rightarrow missing operand a + rightarrow missing operand a b + rightarrow missing operator

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