Question

Code should be written in java Write a program to convert an infix expression to postfix...

Code should be written in java

Write a program to convert an infix expression to postfix expression using stack. Algorithm: a) Create a stack

b) For each character t in the input stream If(t is an operand) append t to the output. Else if (t is a right parenthesis) Pop and append to the output until a left parenthesis is popped (but do not append this parenthesis to the output). Else if(t is an operator or left parenthesis) Pop and append to the output until one of the lower priority than t is encountered or a left parenthesis is encountered or the stack is empty. Push t c)

Pop and append to the output until the stack is empty.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

For the above problem, we need to have the following things into consideration.

  1. We need to put the operands directly to output.
  2. If there are operators then we need to check the precedence
    1. We need to pop all the operators which are of the same or greater precedence from the stack.
    2. Then we can put the operator onto the stack.
  3. So for checking the precedences of the operators, a method is made in the program.

Following is the program in java.



import java.util.Scanner;
import java.util.Stack;

public class ConvertInfixToPostfix
{
   // This is the function used for checking the
   // precedence of the characters
   static int precedence(char ch)
   {
       switch (ch)
       {
       case '+':
       case '-':
           return 1;
  
       case '*':
       case '/':
           return 2;
  
       case '^':
           return 3;
       }
       return -1;
   }
  
   // This is the function which
   // actually converts infix to
   // postfix
   static String infixToPostfix(String exp)
   {
       // String for result
       String result = new String("");
      
       // empty stack
       Stack<Character> stack = new Stack<>();
      
       for (int i = 0; i<exp.length(); ++i)
       {
           char c = exp.charAt(i);
          
           // Adding operand to the output
           if (Character.isLetterOrDigit(c))
               result += c;
          
           // If the scanned character is an '(', push it to the stack.
           else if (c == '(')
               stack.push(c);
          
           // If the scanned character is an ')', pop and output from the stack
           // until an '(' is encountered.
           else if (c == ')')
           {
               while (!stack.isEmpty() && stack.peek() != '(')
                   result += stack.pop();
              
               if (!stack.isEmpty() && stack.peek() != '(')
                   return "Invalid Expression"; // invalid expression                 
               else
                   stack.pop();
           }
           else // Operator
           {
               while (!stack.isEmpty() && precedence(c) <= precedence(stack.peek())){
                   if(stack.peek() == '(')
                       return "Invalid Expression";
                   result += stack.pop();
           }
               stack.push(c);
           }
  
       }
  
       // Popping all the operators
       while (!stack.isEmpty()){
           if(stack.peek() == '(')
               return "Invalid Expression";
           result += stack.pop();
       }
       return result;
   }
  
   // Driver method
   public static void main(String[] args)
   {
       Scanner scan = new Scanner(System.in);
       System.out.print("Infix: ");
       String infix = scan.next();
       String postFix = infixToPostfix(infix);
       System.out.println("PostFix: " + postFix);
   }
}

Output snippet.

That was a nice question to answer
Friend, If you have any doubts in understanding do let me know in the comment section. I will be happy to help you further.
Please like if you think effort deserves like.
Thanks

Add a comment
Know the answer?
Add Answer to:
Code should be written in java Write a program to convert an infix expression to postfix...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • In C programming Language Write a version of the infix-to-postfix conversion algorithm. Write a program that converts an...

    In C programming Language Write a version of the infix-to-postfix conversion algorithm. Write a program that converts an ordinary infix arithmetic expression (assume a valid expression is entered) with single-digit integers For Example: Infix expression (6 + 2) * 5 - 8 / 4 to a postfix expression is  62+5*84/- The program should read the expression into character array infix and use the stack functions implemented in this chapter to help create the postfix expression in character array postfix. The...

  • Write a java code to implement the infix to postfix algorithm as described below: Algorithm convertTo...

    Write a java code to implement the infix to postfix algorithm as described below: Algorithm convertTo Post fix ( infix) // Converts an infix expression to an equivalent postfix expression operatorStack = a new empty stack postfix = anew empty string while (infix has characters left to parse) nextCharacter =next nonblank character of infix switch (nextCharacter) { case variable: Append nextCharacter to postfix break case 'A' operatorStack.push (nextCharacter) break case '+ case '-' : case '*' : case '/' while...

  • Stacks are used by compilers to help in the process of evaluating expressions and generating machine...

    Stacks are used by compilers to help in the process of evaluating expressions and generating machine language code.In this exercise, we investigate how compilers evaluate arithmetic expressions consisting only of constants, operators and parentheses. Humans generally write expressions like 3 + 4and 7 / 9in which the operator (+ or / here) is written between its operands—this is called infix notation. Computers “prefer” postfix notation in which the operator is written to the right of its two operands. The preceding...

  • By using PYTHON language Postfix to Infix using Stack Develop a stack application that can convert...

    By using PYTHON language Postfix to Infix using Stack Develop a stack application that can convert Postfix notation to Infix notation using the following algorithm. In your stack application, you can use only two stacks, one for a stack that can store Postfix notation, and the other is a stack to store infix notation. Also, it would help if you had a function to distinguish between an operation or an operand. Input A B C * + D E /...

  • Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQ...

    Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQUIRED for this program will use two stacks, an operator stack and a value stack. Both stacks MUST be implemented using a linked list. For this program, you are to write functions for the linked list stacks with the following names: int isEmpty (stack); void push (stack, data); data top (stack); void pop (stack); // return TRUE if the stack has no...

  • Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQ...

    Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQUIRED for this program will use two stacks, an operator stack and a value stack. Both stacks MUST be implemented using a linked list. For this program, you are to write functions for the linked list stacks with the following names: int isEmpty (stack); void push (stack, data); data top (stack); void pop (stack); // return TRUE if the stack has no...

  • We as humans write math expression in infix notation, e.g. 5 + 2 (the operators are...

    We as humans write math expression in infix notation, e.g. 5 + 2 (the operators are written in-between the operands). In a computer’s language, however, it is preferred to have the operators on the right side of the operands, i.e. 5 2 +. For more complex expressions that include parenthesis and multiple operators, a compiler has to convert the expression into postfix first and then evaluate the resulting postfix. Write a program that takes an “infix” expression as input, uses...

  • JAVA, please You must write a robust program meaning that your program should not crash with...

    JAVA, please You must write a robust program meaning that your program should not crash with any given data. Data validation must be done any time that user enters an input. Write a program that 1. Gets an infix expression form the user and evaluate the expression using stack ADT a. Finds the postfix equivalent of the given infix expression b. Evaluate the created postfix expression. c. Note: your program should not crash when you enter an invalid expression such...

  • Write a java program to convert and print an infix expression to postfix expression. You can...

    Write a java program to convert and print an infix expression to postfix expression. You can use Java stack methods. (Must read input from System.in) Your main method should be as follow: public static void main(String args[]) { intopost p = new intopost (); String iexp, pexp; //infix postfix expression             try{ Scanner inf = new Scanner (System.in);                     // Read input from KB/ File while(inf.hasNext()){ // read next infix expression                                 iexp = inf.next(); // Assume method name to convert infix...

  • I need assistance with this code. Is there any way I can create this stack class (dealing with infix to postfix then postfix evaluation) without utilizing <stdio.h> and <math.h>? ________...

    I need assistance with this code. Is there any way I can create this stack class (dealing with infix to postfix then postfix evaluation) without utilizing <stdio.h> and <math.h>? ____________________________________________________________________________________________ C++ Program: #include <iostream> #include <string> #include <stdio.h> #include <math.h> using namespace std; //Stack class class STACK { private: char *str; int N; public: //Constructor STACK(int maxN) { str = new char[maxN]; N = -1; } //Function that checks for empty int empty() { return (N == -1); } //Push...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT