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...
java Convert the following Infix expression to a Postfix expression. Show all work                            Infix Expres
java Convert the following Infix expression to a Postfix expression. Show all work                            Infix Expression                                                 Stack                             Postfix Expression ---------------------------------------------------------------------------------------------------------------------------- 8 - 9*(2 + 1/4) + 3*7                                                     (empty)                            (blank) Evaluate the following Postfix expression. Once again, show all work.            Postfix                                               Stack                     Result           ---------------------------------------    --------------------    --------------            2 7 + 12 4 / * 8 5 + -
Using java.util.Stack and java.util.StringTokenizer to write a program that converts an infix expression to a postfix...
Using java.util.Stack and java.util.StringTokenizer to write a program that converts an infix expression to a postfix expression using data from infix.dat. Make sure your program can handle negative number. If the input expression can’t be converted, display error message.(1.5 points) (Should remove parentheses) infix.dat 5 * 6 + -10 3 - 2 + 4 7 ( 3 * 4 - (2 + 5)) * 4 / 2 10 + 6 * 11 -(3 * 2 + 14) / 2 2...
Convert an infix expression to its postfix representation in JAVA
Convert an infix expression to its postfix representation in JAVA
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)
I need an infix to postfix function that accounts for all (, ), {, }, [,...
I need an infix to postfix function that accounts for all (, ), {, }, [, ].. For example. 8-{{(1-[0+4]+8)}} In c++ please.
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.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT