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...
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...
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.
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...
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 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.
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 -...
For question 1 , consider that inside the class Sky, we have already coded the following:...
For question 1 , consider that inside the class Sky, we have already coded the following:     public class Sky      {         private Color color;         public Sky( Color c)           {               color = c;           }       }   Consider the following method header:     public Color getColor(); Is this method a constructor, mutator or accessor?   Inside a method main, we see code like:      Airplane.foo3(34.6); From this, reconstruct the header of method foo3 (which belongs to class...
* 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...
Using STL stack class, implement in C++ a function that converts an infix expression to postfix...
Using STL stack class, implement in C++ a function that converts an infix expression to postfix expression,
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT