Question

In: Computer Science

In Java, write class InfixToPostfixConverter co convert an ordinary infix arithmetic expression (assume a valid expression...

In Java, write class InfixToPostfixConverter co convert an ordinary infix arithmetic expression (assume a valid expression is entered) with single-digit integers (to make things easier) such as

(6 + 2) • 5 - 8 / 4

to a postfix expression. The postfix version (no parentheses are needed) of this infix expression is

6 2 + 5 * 8 4 / -

The program should read the expression into StringBuilder or String infix and use the Stack and Stack Interface class (as found in Lesson 8 Programs Classwork) to help create the postfix expression in StringBuuider (or String) postfix. The algorithm for creating a postfix expression is shown below

Push a left parenthesis ' (' onto the stack.

Append a right parenthesis ') ' to the end of infix.

While the stack is not empty, read infix from left to right and do the following:

     If the current character in infix is a digit, append it to postfix.

     If the current character in infix is a left parenthesis, push it onto the stack.

     If the current character in infix is an operator:

            Pop operators (if there are any) at the top of the stack while they have equal or higher

precedence than the current operator, and append the popped operators to postfix.

     Push the current character in infix onto the stack.

     If the current character in infix is a right parenthesis:

            Pop operators from the top of the stack and append them to postfix until a left parenthesis is at the top of the stack.

            Pop (and discard) the left parenthesis from the stack.

The following arithmetic operations are allowed in an expression:

^ exponentiation

* multiplication

/ division

% remainder

+ addition

- subtraction

Exponents have the highest precedence, multiplication, division and remainder all share the next highest precedence, and addition and subtraction have the lowest precedence.

Some methods you may want to provide are as follows:

Method convertToPostfix, which accepts converts the infix expression to postfix notation by implementing the algorithm described above.

Method is0perator, which determines whether the input parameter c is an operator.

Method precedence, which determines whether the precedence of operator1 (from the infix expression) is less than, equal to or greater than that of operator2 (from the stack). The method returns true if operator1 has lower precedence than operator2. Otherwise, false is returned. Precedence is as defined above.

You will need to use the Stack method peek to perform some of the checks as described above.

Two Sample outputs:

Please enter an infix expression:

(2^5)+(2/4^6)-7

The original infix expression is:

(2^5)+(2/4^6)-7

The expression in postfix notation is:

2 5 ^ 2 4 6 ^ / 7 - +

Please enter an infix expression:

((8*7-5)+2)

The original infix expression is:

((8*7-5)+2)

The expression in postfix notation is:

8 7 * 5 - 2 +

Solutions

Expert Solution

import java.util.*;

class Main{
    
    public static int precedence(char c){
        
        switch (c) {
            
            case '+' :
                return 0;
                
            case '-' :
                return 1;
                
            case '*' : 
            case '/' :
            case '%' :
                return 2;
                
            case '^' : 
                return 3;
            
        }
        
        return -1;
    }
    
    public static boolean isOperator(char c ){
        if(c=='+' || c=='-' || c=='/' || c=='*' || c=='^' || c=='%' )
            return true;
        else 
            return false;
    }
    
    
    public static String convertToPostfix(String exp){
        
         String result = new String(""); 
                 Stack<Character> stack = new Stack<>();         
        
        for (int i = 0; i<exp.length(); ++i) 
                { 
                        char c = exp.charAt(i); 

                        if (Character.isLetterOrDigit(c)) 
                                result += c; 
                        else if (c == '(') 
                                stack.push(c); 
                        else if (c == ')') 
                        { 
                                while (!stack.isEmpty() && stack.peek() != '(') 
                                        result += stack.pop(); 
                                
                                if (!stack.isEmpty() && stack.peek() != '(') 
                                        return "Invalid Expression";                     
                                else
                                        stack.pop(); 
                        } 
                        
                        if(isOperator(c)){
                            
                                while (!stack.isEmpty() && precedence(c) <= precedence(stack.peek())){ 
                                        if(stack.peek() == '(') 
                                                return "Invalid Expression"; 
                                        result += stack.pop(); 
                           } 
                                stack.push(c); 
                        } 
        
                } 
        
                while (!stack.isEmpty()){ 
                        if(stack.peek() == '(') 
                                return "Invalid Expression"; 
                        result += stack.pop(); 
                } 
                return result; 
    }
    
    
    public static void main (String[] args) {
        
        Scanner sc=new Scanner(System.in);
        
        System.out.println("Please enter an infix expression:");
        String expression=sc.nextLine();
        
        System.out.println("The original infix expression is:");
        System.out.println(expression);
        
        String res=convertToPostfix(expression);
        System.out.println("The expression in postfix notation is:");
        System.out.println(res);
        
    }
    
}

If Precedence method is to be strictly should have return type boolean then replace following two method with Precedence method in above code .

public static int getPrecedence(char c){

 switch (c) {
            
            case '+' :
                return 0;
                
            case '-' :
                return 1;
                
            case '*' : 
            case '/' :
            case '%' :
                return 2;
                
            case '^' : 
                return 3;
            
        }
     return -1;
}

public boolean precedence(char ch1,char ch2){
 
  if(getPrecedence(ch1) <= getPrecedence(ch2))
       return true;
  else 
       return false;

}


Related Solutions

Write a java class program to convert from INFIX TO POSTFIX Using stack operations
Write a java class program to convert from INFIX TO POSTFIX Using stack operations
Using a stack, write a program that turns a simple infix arithmetic expression into a postfix...
Using a stack, write a program that turns a simple infix arithmetic expression into a postfix expression. For example, 1 + 2 * 3 becomes 2 3 * 1 +. Also, evaluate the expression to ensure the expression is correct.
Write an algorithm to evaluate an infix expression in Java. Calculate its running time
Write an algorithm to evaluate an infix expression in Java. Calculate its running time
Write a class PostFix that has one method covert that converts an infix expression (as a...
Write a class PostFix that has one method covert that converts an infix expression (as a string input) to a postfix. Then Test it in a different class. code in java.
* the Algorithm: * write a java program to convert infix to postfix create(OpStk) OpStk.push("#") token...
* the Algorithm: * write a java program to convert infix to postfix create(OpStk) OpStk.push("#") token = nextToken() while (token != "#") if (token is an operand) append token to postfix expression else if (token is "(") // Left paren - Start of sub-expr OpStk.push( token ) else if (token is ")") // Right paren - End of sub-expr pop operators off the stack and append to the postfix expression - stop when you've popped a "(" else (token is...
Write a program (preferably in Java) that, given an arithmetic expression, first transforms it to a...
Write a program (preferably in Java) that, given an arithmetic expression, first transforms it to a postfix form, and then computes its value (by using stack-based algorithms). Assume that all the numbers in the arithmetic expression are one-digit numbers, i.e., each of these numbers is either 0, or 1, or 2, ..., or 9. For example, your program should correctly process expressions like 2+3*4, but there is no need to process expressions like 11+22.
An arithmetic expression can be represented in three different formats: infix, prefix, and postfix. In the...
An arithmetic expression can be represented in three different formats: infix, prefix, and postfix. In the infix notation, the operator comes between two operands. In the postfix notation, the operator comes after its two operands. For example, an expression a/b can be transformed to ab/. The following are some examples of the postfix expressions: 2+6*4 Its postfix notation is 2 6 4 * + 2-3+5/4*9-1 Its postfix expression is 2 3 – 5 4 / 9 * + 1 -...
Write a program that performs the following two tasks in java Reads an arithmetic expression in...
Write a program that performs the following two tasks in java Reads an arithmetic expression in an infix form, stores it in a queue (infix queue) and converts it to a postfix form (saved in a postfix queue). Evaluates the postfix expression. Use linked lists to implement the Queue and Stack ADTs. DO NOT USE BUILT IN JAVA CLASSES
**write a java program infix to postfix**showing the expression tree*** I. Input All input data are...
**write a java program infix to postfix**showing the expression tree*** I. Input All input data are from a file "in.dat". The file contains a sequence of infix form expressions, one per line. The character '$' is an end mark. For example, the following file has four infix form expressions: 1 + 2 * 3 ^ ! ( 4 == 5 ) $ 3 * ( 6 - 4 * 5 + 1) + 2 ^ 2 ^ 3 $ 77...
(Convert infix to postfix) Note: Postfix notation is a way of writing expression without using parentheses....
(Convert infix to postfix) Note: Postfix notation is a way of writing expression without using parentheses. For example, the expression ( 11 + 12 ) * 13 would be written as 11 12 + 13 * Assume that ALWAYS there is a space between operands and operators in the input expression. Use two stacks, one to store the operands and one to store the operators. Your program only accpets following operators : ( ) + - / * Write a...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT