Question

Write a Java program that will implement a stack object to convert from either infix notation...

Write a Java program that will implement a stack object to convert from either infix notation to postfix notation or postfix notation to infix notation.  The program will also implement a link list data structure to track all the conversions done. The Program should have a menu like the following as its output:

"Please select what type of conversion you would like to do:

  1. Infix to postfix
  2. Postfix to infix
  3. Print Equations
  4. Exit"
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Screenshot

import java.util.Scanner; import java.util.Stack; /** * Program to convert inf to post and post to inf * Get user has choiceProgram

MyLinkedlist.java

//Create a class node
class MyNode{
   String exp1,exp2;
   char op;
   MyNode next;
   public MyNode(String exp1,String exp2) {
       this.exp1=exp1;
       this.exp2=exp2;
       op='=';
       next=null;
   }
}
//Create orderedr list class
public class MyLinkedList {
   //Instance variable
   MyNode head;
   //Constructor
   public MyLinkedList() { // constructors always have the same name as the class
       head=null;
     }
   //Insert an element last into list
   public void insertItem(String exp1,String exp2) {
       MyNode newNode=new MyNode(exp1,exp2);
       if(head==null) {
           head=newNode;
       }
       else {
           MyNode temp=head;
           while (temp.next != null) {
               temp = temp.next;
       }
       // Insert the new_node at last node
       if(temp.next==null) {
           temp.next = newNode;
        }
    }
}
@Override
public String toString() {
String tempStr = "";
MyNode temp=head;
while(temp.next!=null) {
   tempStr = tempStr+temp.exp1+" "+temp.op+" "+temp.exp2+"\n";
    temp = temp.next;
}
tempStr = tempStr+temp.exp1+" "+temp.op+" "+temp.exp2;
return tempStr;
}

}

Convertor.java

import java.util.Scanner;
import java.util.Stack;
/**
* Program to convert inf to post and post to inf
* Get user has choice for convertion type
* Prompt for expression
* store each conversion in linkedlist
* Display all evaluated expressions
* @author deept
*
*/
public class Convertor {
   //Scanner object for read
   public static Scanner sc=new Scanner(System.in);
   public static void main(String[] args) {
       //Call menu
       int op=menu();
       //Create a linkeslist object
       MyLinkedList list=new MyLinkedList();
       //Loop until exit
       while(op!=4) {
           if(op==1) {
               System.out.println("\nEnter an infix expression: ");
               String inf=sc.nextLine();
               String postfix=infixToPostfix(inf);
               list.insertItem(inf,postfix);
               System.out.println(inf+" = "+postfix);
           }
           else if(op==2) {
               System.out.println("\nEnter an postfix expression: ");
               String postfix=sc.nextLine();
               String inf=postfixToInfix(postfix);
               list.insertItem(postfix,inf);
               System.out.println(postfix+" = "+inf);
           }
           else {
               System.out.println("\nExpressions evaluated:-\n"+list);
           }
           System.out.println();
           op=menu();
       }
       System.out.println("\nGoodbye!!!");
   }
  
   /*
   * Method to get user options
   * Display options
   * Return option
   */
   public static int menu() {
       System.out.println("Please select what type of conversion you would like to do:\n"+
                           "1. Infix to postfix\n2. Postfix to infix\n3. Print Equations\n"+
                           "4. Exit");
       int opt=sc.nextInt();
       //Error check
       while(opt<1 || opt>4) {
           System.out.println("\nERRROR!!!Option should be 1-4.Please Re-enter....\n");
           System.out.println("Please select what type of conversion you would like to do:"+
                    "1. Infix to postfix\n2. Postfix to infix\n3. Print Equations\n"+
                    "4. Exit");
            opt=sc.nextInt();
       }
       sc.nextLine();
       return opt;
   }
   /*
   *Method to get precedence of operator here
   * multiplication division has higher precedence than
   * Addition and subtraction
   */
   public static int precedenceFinder(char op) {
       if(op=='+' || op=='-') {
           return 1;
       }
       else if(op=='*' || op=='/') {
           return 2;
       }
       else {
           return -1;
       }
   }
   /*
   * Method to convert infix to postfix
   * Take an infix expression as input
   * Convert into postfix and return
   */
   public static String infixToPostfix(String infix) {
            String postfix ="";
            //Stack for temporary save
            Stack<Character> stack = new Stack<>();
             //Loop through characters of infix expression
            for (int i = 0; i<infix.length(); ++i)
            {
                char c = infix.charAt(i);
                //Is it digit add into postfix
                if (Character.isLetterOrDigit(c)) {
                   postfix+=c;
                }
                //Check for opening brace
                else if (c == '(') {
                   stack.push(c);
                }
                //Check for closing brace
                else if (c == ')')
                {
                   //The take elements from stack to add into postfix
                    while (!stack.isEmpty() && stack.peek() != '(') {
                       postfix+=stack.pop();
                    }
                    //If nothing inside stack means invalid expression
                    if (!stack.isEmpty() && stack.peek() != '(')
                        return "Invalid Expression";             
                    else
                        stack.pop();
                }
                //If operator get then find out precedence
                else
                {
                    while (!stack.isEmpty() && precedenceFinder(c) <= precedenceFinder(stack.peek())){
                        if(stack.peek() == '(') {
                           return "Invalid Expression";
                        }
                        postfix += stack.pop();
                    }
                    stack.push(c);
                }
         
            }
           //Pop until end of stack
            while (!stack.isEmpty()){
                if(stack.peek() == '(') {
                   return "Invalid Expression";
                }
                postfix += stack.pop();
             }
            return postfix;
        }
     
   /**
   * Method to generate infix from given postfix expression
   * Loop through each character to seperate operator and operand
   * Use stack for temporary storage and evaluate infix and return
   * @param exp
   * @return
   */
   public static String postfixToInfix(String post)
   {
       //Temporary storage
         Stack<String> stack = new Stack<String>();
         //Loop until end of th estring
         for (int i = 0; i < post.length(); i++)
         {
             //Check fo roperand
             if (Character.isLetterOrDigit(post.charAt(i))) {
               stack.push(post.charAt(i) + "");
             }
             //Check for operator
             else
             {
                 String op1 = stack.peek();
                 stack.pop();
                 String op2 = stack.peek();
                 stack.pop();
                 stack.push("(" + op2 + post.charAt(i) + op1 + ")");
             }
         }
     
        //last element from stack
         return stack.peek();
   }
}

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

Output

Please select what type of conversion you would like to do:
1. Infix to postfix
2. Postfix to infix
3. Print Equations
4. Exit
1

Enter an infix expression:
2+5
2+5 = 25+

Please select what type of conversion you would like to do:
1. Infix to postfix
2. Postfix to infix
3. Print Equations
4. Exit
2

Enter an postfix expression:
25+
25+ = (2+5)

Please select what type of conversion you would like to do:
1. Infix to postfix
2. Postfix to infix
3. Print Equations
4. Exit
3

Expressions evaluated:-
2+5 = 25+
25+ = (2+5)

Please select what type of conversion you would like to do:
1. Infix to postfix
2. Postfix to infix
3. Print Equations
4. Exit
4

Goodbye!!!

Add a comment
Know the answer?
Add Answer to:
Write a Java program that will implement a stack object to convert from either infix notation...
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
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