Question

In: Computer Science

JAVA PROGRAM Question : Design and implement two classes called InfixToPostfix and PostFixCalculator. The InfixToPrefix class...

JAVA PROGRAM

Question : Design and implement two classes called InfixToPostfix and PostFixCalculator. The InfixToPrefix class converts an infix expression to a postfix expression. The PostFixCalculator class evaluates a postfix expression. This means that the expressions will have already been converted into correct postfix form. Write a main method that prompts the user to enter an expression in the infix form, converts it into postfix, displays the postfix expression as well as it's evaluation. For simplicity, use only these operators, + , - , * , / and %.

I need help answering the programming question, not sure how this really functions. If you can please explain how it works with comments. Thank you I greatly appreciate the help.

Solutions

Expert Solution

The below code illustartes two methods.

infixToPostfix : converts infix expression to postfix expression

postFixCalculator : calculates the value of postfix expression.

The code is commented for understanding each logic.

import java.util.*;
  
class Main
{ 
   // this method returns the precedence of operators
    static int Preced(char c) 
    { 
        switch (c)    // define some integer value as per the order of precedence
        { 
        case '+': 
        case '-': 
            return 1; 
       
        case '*': 
        case '/': 
        case '%': 
            return 2; 
       
        case '^': 
            return 3; 
        } 
        return 0; 
    } 
       
    // this method converts infix expression to postfix expression 
    static String infixToPostfix(String infix) 
    { 
        // initialize one  empty stack 
        Stack<Character> st = new Stack<>(); 
        
        // initialize one empty string 
        String postfix = new String(""); 
          
         
        for (int i = 0; i<infix.length(); i++) 
        { 
            char c = infix.charAt(i); 
              
             // if the character is operand, add it to output 
            if (Character.isLetterOrDigit(c))   // this built in function returns true if the char is letter or digit
                postfix += c; 
               
            // if the character is '(', push it to stack
            else if (c == '(') 
                st.push(c); 
              
            //  if the character is ')', pop and add it to output string until '(' is found
            else if (c == ')') 
            { 
                while (!st.isEmpty() && st.peek() != '(') 
                    postfix = postfix+ st.pop(); 
                
                // if '(' is not found at the end then its not an infix expression
                if (!st.isEmpty() && st.peek() != '(') 
                    return "Wrong expression, not an infix expression"; // invalid expression                 
                else
                    st.pop(); 
            } 
            else // if an operator is found
            { 
                // check the precedence, while the precedence of the current operator is less than the precedence of operators in stack,
                //remove the operators from stack and add them to the result
                while (!st.isEmpty() && Preced(c) <= Preced(st.peek())){ 
                    if(st.peek() == '(') 
                        return "Wrong expression, not an infix expression"; 
                    postfix = postfix +  st.pop(); 
             } 
                st.push(c);  // at the end push the current operator into the stack
            } 
       
        } 
        // at the end pop all the operators from stack and add them to the result
        while (!st.isEmpty()){ 
            if(st.peek() == '(') 
                return "Wrong expression, not an infix expression"; 
            postfix = postfix + st.pop(); 
         } 
        return postfix; 
    } 
    
    static int postfixCalculator(String postfix) 
    { 
        
        Stack<Integer> st=new Stack<>(); 
          
        // loop through all the characters
        for(int i=0;i<postfix.length();i++) 
        { 
            char c=postfix.charAt(i); 
              
            // if operand (digit) push into stack 
            if(Character.isDigit(c)) 
            st.push(c - '0'); 
              
            // if operator, pop two elements from top and do the calculation
            // push the result back to the stack
            else
            { 
                int a= st.pop(); 
                int b = st.pop(); 
                  
                switch(c) 
                { 
                    case '+': 
                    st.push(b+a); 
                    break; 
                      
                    case '-': 
                    st.push(b- a); 
                    break; 
                      
                    case '/':
                    st.push(b/a); 
                    break; 
                      
                    case '*': 
                    st.push(b*a); 
                    break; 
              } 
            } 
        } 
        return st.pop();     // at the end return the single element from the stack which is the result
    } 
    
     
    public static void main(String[] args)  
    { 
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the infix expression: ");
        String infix = sc.nextLine();
        String postfix = infixToPostfix(infix); 
        System.out.println("The postfix expression is: "+postfix );
        int res = postfixCalculator(postfix);
        System.out.println("The value of the postfix expression is: "+ res);
    } 
} 

Output sample screenshot:


Related Solutions

Question : Design and implement two classes called InfixToPostfix and PostFixCalculator. The InfixToPrefix class converts an...
Question : Design and implement two classes called InfixToPostfix and PostFixCalculator. The InfixToPrefix class converts an infix expression to a postfix expression. The PostFixCalculator class evaluates a postfix expression. This means that the expressions will have already been converted into correct postfix form. Write a main method that prompts the user to enter an expression in the infix form, converts it into postfix, displays the postfix expression as well as it's evaluation. For simplicity, use only these operators, + ,...
JAVA Specify, design, and implement a class called PayCalculator. The class should have at least the...
JAVA Specify, design, and implement a class called PayCalculator. The class should have at least the following instance variables: employee’s name reportID: this should be unique. The first reportID must have a value of 1000 and for each new reportID you should increment by 10. hourly wage Include a suitable collection of constructors, mutator methods, accessor methods, and toString method. Also, add methods to perform the following tasks: Compute yearly salary - both the gross pay and net pay Increase...
The answer should be in JAVA. You will design and implement two classes to support a...
The answer should be in JAVA. You will design and implement two classes to support a client program, RockPaperScissorsGame.java, to simulate Rock-Paper-Scissors game. Read and understand the client program to find out the requirements for the HandShape and Player classes. The rules of the Rock-Paper-Scissors game are:     Scissors✌️ beats Paper✋ that beats Rock✊ that beats Scissors✌️ Additionally, to simplify the game logic (and complexify a little bit the HandSahpe class) , two players cannot show the same hand shape....
The answer should be in JAVA. You will design and implement two classes to support a...
The answer should be in JAVA. You will design and implement two classes to support a client program, RockPaperScissorsGame.java, to simulate Rock-Paper-Scissors game. Read and understand the client program to find out the requirements for the HandShape and Player classes. The rules of the Rock-Paper-Scissors game are:     Scissors✌️ beats Paper✋ that beats Rock✊ that beats Scissors✌️ Additionally, to simplify the game logic (and complexify a little bit the HandSahpe class) , two players cannot show the same hand shape....
JAVA - Design and implement a class called Flight that represents an airline flight. It should...
JAVA - Design and implement a class called Flight that represents an airline flight. It should contain instance data that represent the airline name, the flight number, and the flight’s origin and destination cities. Define the Flight constructor to accept and initialize all instance data. Include getter and setter methods for all instance data. Include a toString method that returns a one-line description of the flight. Create a driver class called FlightTest, whose main method instantiates and updates several Flight...
In Java, design and implement a class called Cat. Each Cat class will contain three private...
In Java, design and implement a class called Cat. Each Cat class will contain three private variables - an integer representing its speed, a double representing its meowing loudness, and a String representing its name. Using the Random class, the constructor should set the speed to a random integer from 0 to 9, the meowing loudness to a random double, and the name to anything you want; the constructor should take no parameters. Write “get” and “set” methods for each...
1) Design an implement a program that created and exception class called StringTooLongException, designed to be...
1) Design an implement a program that created and exception class called StringTooLongException, designed to be thrown when a string is discovered that has too many characters in it. Create a driver that reads in strings from the user until the user enters DONE. If a string that has more then 5 characters is entered, throw the exception. Allow the thrown exception to terminate the program 2) Create a class called TestScore that has a constructor that accepts an array...
Java program Create two classes based on the java code below. One class for the main...
Java program Create two classes based on the java code below. One class for the main method (named InvestmentTest) and the other is an Investment class. The InvestmentTest class has a main method and the Investment class consists of the necessary methods and fields for each investment as described below. 1.The Investment class has the following members: a. At least six private fields (instance variables) to store an Investment name, number of shares, buying price, selling price, and buying commission...
Writing Classes I Write a Java program containing two classes: Dog and a driver class Kennel....
Writing Classes I Write a Java program containing two classes: Dog and a driver class Kennel. A dog consists of the following information: • An integer age. • A string name. If the given name contains non-alphabetic characters, initialize to Wolfy. • A string bark representing the vocalization the dog makes when they ‘speak’. • A boolean representing hair length; true indicates short hair. • A float weight representing the dog’s weight (in pounds). • An enumeration representing the type...
JAVA A simple Class in a file called Account.java is given below. Create two Derived Classes...
JAVA A simple Class in a file called Account.java is given below. Create two Derived Classes Savings and Checking within their respective .java files. (modify display() as needed ) 1. Add New private String name (customer name) for both, add a New int taxID for Savings only. 2. Add equals() METHOD TO CHECK any 2 accounts Demonstrate with AccountDemo.java in which you do the following: 3. Create 1 Savings Account and 3 Checking Accounts, where 2 checkings are the same....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT