Question

In: Computer Science

2.) Postfix to infix translator (NOTE: This is NOT the evaluator you have already coded!) •...

2.) Postfix to infix translator (NOTE: This is NOT the evaluator you have already coded!) • Create a java class called PostfixToInfixTranslator that includes a main method. • The code you write should prompt the user for an expression in postfix notation and use ArrayStack to output the equivalent expression in infix. • See the following session: Enter a postfix expression: 3 4 + 2 * In infix notation that is: ((3+4)*2) Translate another expression [y/n]? y Enter a postfix expression: 4 2 + 3 5 1 - * + In infix notation that is: ((4+2)+(3*(5-1))) Translate another expression [y/n]? n • NOTE: The postfix expression has to accept spaces, double digit numbers, and negative numbers. So .charAt() is not a good approach. Maybe a scanner on a string?

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

StackADT, EmptyCollectionException, and ArrayStack code already below, please use these.


public interface StackADT<T> //Provide layout of what we want something to do w/o supplying the way it gets done = interface
{
   public void push( T element) ;
  
   public T pop () throws EmptyCollectionException;
  
   public T peek() throws EmptyCollectionException;
  
   public boolean isEmpty();
  
   public int size();
}


public class EmptyCollectionException extends Exception
{
  
   private static final long serialVersionUID = 358083002087971606L;

   public EmptyCollectionException()
   {
       super();
   }
  
   public EmptyCollectionException(String msg)
   {
       super(msg);
   }
}

import java.util.Arrays;

public class ArrayStack<T> implements StackADT<T> //We agree to supply all functions that we say exist StackADT Functions correlate to ArrayStack
{
   private final static int DEFAULT_CAPACITY = 100;
   private int top;
   private T[] stack;
  
   public ArrayStack()
   {
       this(DEFAULT_CAPACITY);
   }
  
   @SuppressWarnings("unchecked")
   public ArrayStack(int initialCapacity)
   {
       top = 0;
       stack = (T[]) new Object [initialCapacity]; //Have to cast Object Array to T array in order for placeholder to work. Java just works like that.
   }
  
   public void push( T element)
   {
       if(size() == stack.length)
           expandCapacity();
       stack [top] = element;
       ++top;
   }
  
   public T pop() throws EmptyCollectionException
   {
       if(isEmpty())
           throw new EmptyCollectionException();
       --top;
       T result = stack[top];
       stack [top] = null; // Top before that ends up being empty; Makes it clean
       return result;
   }
  
   public T peek() throws EmptyCollectionException
   {
       if(isEmpty())
           throw new EmptyCollectionException();
       return stack[top -1];
   }
  
   public int size()
   {
       return top;
   }
  
   public boolean isEmpty()
   {
       // Even shorter
       return top ==0;
       // Short
//       boolean a = top == 0;
//       return a;
       // long way
//       if(top==0)
//           return true;
//       else
//           return false;
   }
  
   public void expandCapacity()
   {
       stack = Arrays.copyOf(stack, stack.length * 2); //Would values stay the same but only place in memory changes? Hexa decimal #'s?
   }
  
   public String toString()
   {
       String output = "ArrayStack-> [ ";
       for(int i =top-1; i >=0 ; i--)
       {
           output+= stack[i].toString() + " ";
       }
      
       output+= "]";
       return output;
   }
}

WHAT I ALREADY HAVE CODED IN TRANSLATOR, PLEASE HELP. I don't know how to allow spaces, double digits, and negative numbers, and also how to loop the scanner input.

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

public class PostfixToInfixTranslator
{

   public static void main(String[] args) throws EmptyCollectionException
   {
       PostfixToInfixTranslator obj = new PostfixToInfixTranslator();
       Scanner sc = new Scanner(System.in);
       System.out.print("Postfix : ");
       String postfix = sc.next();
       System.out.println("Infix : " +obj.convert(postfix));
      

   }

   private boolean isOperator(char c)
   {
       if(c == '+' || c== '-' || c== '*' || c=='/' || c=='^')
           return true;
       return false;
   }
  
   public String convert(String postfix) throws EmptyCollectionException
   {
       ArrayStack<String> s = new ArrayStack<>();
      
       for(int i =0; i < postfix.length(); i++)
       {
           char c = postfix.charAt(i);
           if(isOperator(c))
           {
               String b = s.pop();
               String a = s.pop();
               s.push("("+a+c+b+")");
           }
           else
               s.push(""+c);
       }
       return s.pop();
   }

}


Solutions

Expert Solution

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class PostfixToInfixTranslator {

    public static void main(String[] args) throws EmptyCollectionException {
        PostfixToInfixTranslator obj = new PostfixToInfixTranslator();
        try {
            BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

            String cmd = "y";
            String[] postfix;
            while (cmd.equalsIgnoreCase("y")) {
                System.out.print("Enter a Postfix expression : ");
                postfix = input.readLine().split(" ");
                System.out.println("Infix Notation is : " + obj.convert(postfix));
                System.out.println("Translate another expression[y/n]?");
                cmd = input.readLine();
            }
        } catch (IOException ex) {
        }


    }

    private boolean isOperator(String c) {
        if (c.equalsIgnoreCase("+") || c.equalsIgnoreCase("-")
                || c.equalsIgnoreCase("*") || c.equalsIgnoreCase("/")
                || c.equalsIgnoreCase("^"))
            return true;
        return false;
    }

    public String convert(String[] postfix) throws EmptyCollectionException {
        ArrayStack<String> s = new ArrayStack<>();

        for (int i = 0; i < postfix.length; i++) {
            String c = postfix[i];

            if (isOperator(c)) {
                String b = s.pop();
                String a = s.pop();
                s.push("(" + a + c + b + ")");
            } else
                s.push(c);
        }
        return s.pop();
    }

}


Related Solutions

(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...
Implement an infix expression to postfix expression convertor in C++. Note: - Support +, -, *,...
Implement an infix expression to postfix expression convertor in C++. Note: - Support +, -, *, /, ( and ) in infix expressions. - Operands will be nonnegative only. - Assume infix expressions are valid and well formatted (one blank space to separate operand/operator) For example, - 3 * 4 + 5 ➔ 3 4 * 5 + - 3 + 4 * 5 ➔ 3 4 5 * + - (3 + 4) * (5 + 6) ➔ 3...
Please make sure that these infix and postfix equations have these answers nothing else: Infix: (3...
Please make sure that these infix and postfix equations have these answers nothing else: Infix: (3 * 4 - (2 + 5)) * 4 / 2 = valid expression 10 + 6 * 11 -(3 * 2 + 14) / 2 = valid expression Postfix: 9 3 / 6 / 4 * 10 - = -8 9 3 / 6 / 4 * -10 - = 12 (a) Using java.util.stack to write a java program to validate and calculate the...
In Python, I have a turtle that is already coded to move in correlation with the...
In Python, I have a turtle that is already coded to move in correlation with the keys I set (I can control the turtle). I need to put a second turtle in that moves WHILE the first turtle is moving and being controlled. The second turtle needs to do the following while the first turtle is still listening and being controlled: -It needs to begin facing a random direction -It needs to move at a speed of .5 the entire...
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.
Convert an infix expression to its postfix representation in JAVA
Convert an infix expression to its postfix representation in JAVA
2. Convert the following infix form expression into the postfix form expression by using a stack:...
2. Convert the following infix form expression into the postfix form expression by using a stack: A+(B*(C-D)+E)/F-G*H Show the stack after each push/pop.
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 + -
PostFixEvaluator.java import java.util.Stack; import java.util.Scanner; /** * Represents an integer evaluator of postfix expressions. Assumes *...
PostFixEvaluator.java import java.util.Stack; import java.util.Scanner; /** * Represents an integer evaluator of postfix expressions. Assumes * the operands are constants. * * @author Java Foundations * @version 4.0 */ public class PostfixEvaluator {    private final static char ADD = '+';    private final static char SUBTRACT = '-';    private final static char MULTIPLY = '*';    private final static char DIVIDE = '/';    private Stack stack;    /**    * Sets up this evaluator by creating a...
C++ program that can take in EITHER "infix" or "prefix" (NOT POSTFIX) and transforms it into...
C++ program that can take in EITHER "infix" or "prefix" (NOT POSTFIX) and transforms it into the other one. Should use stack and have infixToPrefix and prefixToInfix functions with a simple main function for execution.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT