Question

In: Computer Science

**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 > ( 2 - 1 ) + 80 / 4 $
   ! ( 2 + 3 * 4 >= 10 % 6 ) && 20 != 30 || 45 / 5 == 3 * 3 $

Each expression is a sequence of tokens (i.e., constant integers,
operators, and end mark) separated by spaces. There is no variable.


II. Output

   Output data and related information are sent to the screen.
Your program should do the following for each expression:

   (1) printing the expression before it is manipulated;
   (2) showing the converted postfix form expression;
   (3) showing the expression tree;
   (4) printing the fully parenthesized infix form expression;
   (5) reporting the value of the expression.


III. Operators

   The following operators are considered. They are listed in the
decreasing order of precedence.

   Token            Operator            Associativity

    !               logical not         right-to-left
    ^               exponentiation      right-to-left
    *  /  %         multiplicative      left-to-right
    +  -            additive            left-to-right
    <  <=  >  >=    relational          left-to-right
    ==  !=          equality            left-to-right
    &&              logical and         left-to-right
    ||              logical or          left-to-right


IV. Other Requirements

   Since a large amount of information are to be displayed on the
screen, it is mandatory for your program to provide users a prompting
message such as

          Press <Enter> to continue ...

after each expression is processed, so that users have the chance to
check the output of your program carefully.


V. Algorithm: Infix_to_postfix conversion

  Input:  An infix form expression E = t1 t2 t3 ... $,
          which is a sequence of tokens.
  Output: The postfix form expression of E.

  Algorithm: 
  {
    do {
      get the next token t;
      case (t) {
         operand: place t onto the output;
                  break;
        operator: while (stack s is not empty
                    && stacktop(s) is not a left parenthesis)
                    && precedence(stacktop(s)) >= precedence(t)
                       // assuming left-to-right associativity, 
                       // not for the exponentiation operator ^, 
                       // which has right-to-left associativity 
                  {
                        pop(x,s);
                        place x onto the output;
                  }
                  push(t,s);
                  break;
               (: push(t,s);
                  break;
               ): while (stacktop(s) is not a left parenthesis) {
                      pop(x,s);
                      place x onto the output;
                  }
                  pop(x,s);
                  break;
        end mark: while (stack s is not empty) {
                      pop(x,s);
                      place x onto the output;
                  }
                  place the end mark onto the output;
                  break;
      }
    } while (t is not the end mark);
  }

Solutions

Expert Solution

private int getPreference(char c){
        if(c=='+'|| c=='-') return 1;
        else if(c=='*' || c=='/') return 2;
        else return -1;
    }
    private int calculatePostFix(List<String> postFixList){
        Stack<Integer> stack = new Stack<>();
        for(int i=0;i<postFixList.size();i++){
            String word = postFixList.get(i);
            if(word.length()==1 && (word.charAt(0)=='+'||word.charAt(0)=='-'||word.charAt(0)=='*'||word.charAt(0)=='/')){
                int number2 = stack.pop();
                int number1 = stack.pop();
                if(word.charAt(0)=='+'){
                    int number = number1+number2;
                    stack.push(number);
                }else if(word.charAt(0)=='-'){
                    int number = number1-number2;
                    stack.push(number);
                }else if(word.charAt(0)=='*'){
                    int number = number1*number2;
                    stack.push(number);
                }else{
                    int number = number1/number2;
                    stack.push(number);
                }
            }else{
                int number = Integer.parseInt(word);
                stack.push(number);
            }
        }
        return stack.peek();
    }
    private List<String> getPostFixString(String s){
        Stack<Character> stack = new Stack<>();
        List<String> postFixList = new ArrayList<>();
        boolean flag = false;
        for(int i=0;i<s.length();i++){
            char word = s.charAt(i);
            if(word==' '){
                continue;
            }
            if(word=='('){
                stack.push(word);
                flag = false;
            }else if(word==')'){
                flag = false;
                while(!stack.isEmpty()){
                    if(stack.peek()=='('){
                        stack.pop();
                        break;
                    }else{
                        postFixList.add(stack.pop()+"");
                    }
                }
            }else if(word=='+' || word=='-' || word=='*' || word=='/'){
                flag = false;
                if(stack.isEmpty()){
                    stack.push(word);
                }
                else{
                    while(!stack.isEmpty() && getPreference(stack.peek())>=getPreference(word)){
                        postFixList.add(stack.pop()+"");
                    }
                    stack.push(word);
                }
            }else{
                if(flag){
                    String lastNumber = postFixList.get(postFixList.size()-1);
                    lastNumber+=word;
                    postFixList.set(postFixList.size()-1, lastNumber);
                }else
                postFixList.add(word+"");
                flag = true;
            }
        }
        while(!stack.isEmpty()){
            postFixList.add(stack.pop()+"");
        }
        return postFixList;
    }
    public int calculate(String s) {
        List<String> postFixString = getPostFixString(s);
        return calculatePostFix(postFixString);
    }

Related Solutions

Write a program that takes an infix expression as input and produces a postfix expression. The...
Write a program that takes an infix expression as input and produces a postfix expression. The infix and postfix expressions are in the form of vectors of strings. We will test with a main method that takes a file name as input from the command line. We will test your implementation using printPostFix() method.   There are sample input and output files in this folder. You may edit the header file. Example 1 infix expression = apple + banana * cat...
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.
* 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 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 Java 8. Write a program that reads an expression in postfix notation, builds the expression...
Using Java 8. Write a program that reads an expression in postfix notation, builds the expression tree and prints the expression in prefix and infix notation and evaluates the expression. (Hint use a stack)
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.
C++ Data Structure Write a program to change following infix expressions to postfix expressions using a...
C++ Data Structure Write a program to change following infix expressions to postfix expressions using a stack a) D-B+C b) C*D+A*B c) (A*B)*C+D*F-C d) (A-4*(B-C)-D/E)*F
(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...
Postfix Evaluation (JAVA PROGRAMMING) Write class PostfixEva1uator that evaluates a postfix expression such as 6 2...
Postfix Evaluation (JAVA PROGRAMMING) Write class PostfixEva1uator that evaluates a postfix expression such as 6 2 + 5 * 8 4 / - The program should read a postfix expression consisting of single digits and operators into a StringBuilder, The program should read the expression and evaluate it (assume it's valid). The algorithm to evaluate a postfix expression is shown below. Use +, -, *, /, and ^. ^ is the exponent. Append a right parenthesis ') ' to the...
Write a C++ program that converts an infix expression, which includes (, ), +, -, *,...
Write a C++ program that converts an infix expression, which includes (, ), +, -, *, and / operations to postfix notation. The program should allow the user to enter an infix expression using lower case characters, then it will display the result of conversion on the screen. (Note: Use the STL stack class to accomplish the solution.).
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT