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 InfixToPosfix.java that

ID: 3905952 • Letter: D

Question

Description of program: You are to write a program name InfixToPosfix.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 expic?wi: Von can consider only single digit for number Sample Output: Enter infix expression: (x+1)(x- 2)/4 Converted expression: x 1x 2-*4/ Enter infix expression: 1 2+ 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

Program


package infixtopostfixvalidation;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Stack;


public class InfixtoPostFixValidation {

   
    public static boolean isOperand(char c) {
        return ('0' <= c && c <= '9') || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
    }

    public static int getThePrecedence(char c){
        if(c == '^')
            return 6;
        if(c == '*' || c == '/')
            return 5;
        if(c == '-' || c == '+')
            return 4;
        if(c == '>' || c == '<' || c == '=' || c == '#')
            return 3;
        if(c == '.')
            return 2;
        if(c == '|')
            return 1;
        return 0;
    }


    public static boolean checkParenthesis(String s){
        int stack = 0;
        for (int i = 0; i < s.length(); ++i) {
            char c = s.charAt(i);
            if(c == '(')
                ++stack;
            else if(c == ')'){
                --stack;
                if(stack < 0)
                    return false;
            }
        }
        return stack == 0;
    }

    public static String parseInfixToPostfix(String s) {
        StringBuilder out = new StringBuilder("");
        Stack<Character> stack = new Stack<>();

        for (int i = 0; i < s.length(); ++i) {
            char c = s.charAt(i);

            if (isOperand(c)) {
                out.append(c);
                continue;
            }

            if (c == '(') {
                stack.add(c);
                continue;
            }

            if (c == ')') {
                char ch = stack.pop();

                //create a temporary stringbuilder to check if the expression has an empty parenthesis ()

                StringBuilder temp = new StringBuilder("");
                while (ch != '(') {
                    temp.append(ch);
                    ch = stack.pop();
                }

                if(temp.length() == 0) //empty parenthesis
                    return ""; //will be invalidated by the postfix checker

                out.append(temp.toString());
                continue;
            }

            //here are only operators
            if(stack.empty()){
               stack.push(c);
            }

            else{
                while(!stack.empty() && ( getThePrecedence(stack.peek()) >= getThePrecedence(c) ))
                    out.append(stack.pop());
                stack.push(c);
            }
        }

        while(!stack.empty())
            out.append(stack.pop());

        return out.toString();
    }

    public static boolean postFixValidate(String s){
        if(s.equals(""))
            return false;

        int stack = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if(c == '(' || c == ')')
                continue;

            if(isOperand(c)){
                ++stack;
            }
            else {
                stack -= 2;
                if(stack < 0)
                    return false;
                ++stack;
            }
        }
        return stack == 1;
    }

    public static boolean lexicalAnalysis(String s){
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if(isOperand(c) == false && getThePrecedence(c) == 0 && c != '(' && c != ')')
                return false;
        }
        return true;
    }


    public static void main(String[] args) throws IOException
    {
       BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        PrintStream out = new PrintStream(System.out);
System.out.print("Please enter input string : ");
        while (true) {
            String s = in.readLine();

            if (lexicalAnalysis(s)) {
                if(checkParenthesis(s))
                {
                    String postfix = parseInfixToPostfix(s);
                    if(postFixValidate(postfix))
                    {
                        System.out.println(postfix);
                    }
                    else{
                        out.println("Syntax Error!");
                    }
                }
                else{
                    out.println("Syntax Error2!");
                }
            } else {
                out.println("Lexical Error!");
            }
        }
    }

    }