Question

In: Computer Science

Write a class Lab7 that reads and evaluates postfix expressions contained in a file. Each line...

Write a class Lab7 that reads and evaluates postfix expressions contained in a file. Each line of the file contains a postfix expression with integers as operands and ‘+’, ‘-’, ‘*’ and ‘/’ as operators. Consecutive operands and operators are separated by spaces. Note the following requirements for the lab: • The main method in Lab7.java should do the following. 1. ask the user for the name of the file containing the expressions, 2. for each line of the file, read the postfix expression, call the method evaluatePostfix on this expression, and print the expression and its evaluation on the console. • The method to evaluate the postfix expression in Lab7.java must have the following signature: public static int evaluatePostfix(String expr). Your implementation must use the Scanner class to parse each line of the file to obtain the postfix expressions and then use a stack to evaluate each of these expressions. Test your code using lab7.dat as your input data file. You will also need the following files : StackInterface.java, StackArrayListBased.java, StackException.java

/** Implementation of a Stack Class using an ArrayList; we consider the
 * top of the stack to be the first element in the ArrayList. Hence a
 * push adds an element in the front of the vector, and a
 * pop removes the first element of the vector.
 * @authors Sharmin Jahan, Sandip Sen
 */
import java.util.ArrayList;

public class StackArrayListBased implements StackInterface {
    /** ArrayList used for the stack */
    private ArrayList stack;

    /** default constructor */
    public StackArrayListBased() {
        stack = new ArrayList();
    }  // end default constructor


    /** Tests if this stack has no elements.
     * @return true if this list has no elements;
     * false otherwise.
     */
    public boolean isEmpty() {
        return stack.isEmpty();
    }  // end isEmpty


    /** Adds an item to the top of a stack.
     *Postcondition: If insertion is successful, newItem is on the top
     * of the stack
     * @param newItem is the item to be added.
     * @throws some implementations may throw StackException when
     * newItem cannot be placed on the stack.
     */
    public void push(E newItem) throws StackException {
        stack.add(0, newItem);
    }  // end push

    /**
     * Removes all the items from the stack.
     * PostCondition: Stack is empty.
     */
    public void popAll() {
        stack.clear();
    }  // end popAll

    /**
     * Removes the top of a stack.
     * @return If the stack is not empty, the item that was added most
     * recently is removed from the stack and returned.
     * @throws StackException if the stack is empty.
     */
    public E pop() throws StackException {
        if (!isEmpty()) {
            return stack.remove(0);
        }
        else {
            throw new StackException("StackException on " +
                    "pop: stack empty");
        }  // end if
    }  // end pop

    /**  Retrieves the top of a stack.
     * @return If the stack is not empty, the item that was added most
     * recently is returned. The stack is unchanged.
     * @throws StackException if the stack is empty.
     */
    public E peek() throws StackException {
        if (!isEmpty()) {
            return stack.get(0);
        }
        else {
            throw new StackException("Stack exception on " +
                    "peek - stack empty");
        }  // end if
    }  // end peek
}  // end StackArrayListBased
/** Generic Stack Interface */
public interface StackInterface {

    /** Determines whether the stack is empty.
     * @return true if the stack is empty; false otherwise
     */
    public boolean isEmpty();
    
    /**
     * Removes all the items from the stack.
     * PostCondition: Stack is empty.
     */
    public void popAll();
    
    /** Adds an item to the top of a stack.     
     *Postcondition: If insertion is successful, newItem is on the top
     * of the stack
     * @param newItem is the item to be added.
     * @throws Some implementations may throw StackException when
     * newItem cannot be placed on the stack.
     */
    public void push(E newItem) throws StackException;

    /**
     * Removes the top of a stack.
     * @return If the stack is not empty, the item that was added most
     * recently is removed from the stack and returned.
     * @throws StackException if the stack is empty.
     */
    public E pop() throws StackException;
  
  
    /**  Retrieves the top of a stack.  
     * @return If the stack is not empty, the item that was added most
     * recently is returned. The stack is unchanged.
     * @throws StackException if the stack is empty.
     */
    public E peek() throws StackException;
 
    

}  // end StackInterface
public class StackException 
             extends java.lang.RuntimeException {
  public StackException(String s) {
    super(s);
  }  // end constructor
}  // end StackException

lab7.dat

5 4 - 12 - 10 62 + /
10 7 * 43 - 15 / 17 39 - +
22 11 / 19 * 14 2 + 2 * -
40 3 * 66 - 5 / 29 +

Solutions

Expert Solution

The code for lab7.java is as follows:

package SinglePackage;

import java.io.*;
import java.util.*;


public class Lab7  
{ 
    // Method to evaluate value of a postfix expression 
    public static int evaluatePostfix(String exp) 
    { 
        //create a stack 
        StackArrayListBased stack=new StackArrayListBased(); 
        String[] c=exp.split(" "); 
        // Scan all characters one by one 
        for(int i=0;i<c.length;i++) 
        { 
           
              
            // If the scanned character is an operand (number here), 
            // push it to the stack. 
            if(c[i].chars().allMatch( Character::isDigit)) 
            stack.push(Integer.parseInt(c[i])); 
              
            //  If the scanned character is an operator, pop two 
            // elements from stack apply the operator 
            else
            { 
                int val1 = stack.pop(); 
                int val2 = stack.pop(); 
                  
                switch(c[i]) 
                { 
                    case "+": 
                    stack.push(val2+val1); 
                    break; 
                      
                    case "-": 
                    stack.push(val2- val1); 
                    break; 
                      
                    case "/": 
                    stack.push(val2/val1); 
                    break; 
                      
                    case "*": 
                    stack.push(val2*val1); 
                    break; 
              } 
            } 
        } 
        return stack.pop();     
    } 
      
    // Driver program to test above functions 
    public static void main(String[] args) throws IOException  
    { 
        /*String exp1="2 3 * 1 +"; 
        String exp2 ="40 3 * 66 - 5 / 29 +";
        System.out.println("postfix evaluation: "+evaluatePostfix(exp2));*/
        String s=null;
        File file = new File("./lab7.dat"); 
        Scanner sc = new Scanner(file); 
        while (sc.hasNextLine()) {
                s=sc.nextLine();
            System.out.println("The evaluated value of "+s+" is "+evaluatePostfix(s));
         }   
            sc.close();
     } 
       
} 

StackArrayListBased.java

package SinglePackage;

import java.util.ArrayList;

public class StackArrayListBased implements StackInterface {
    /** ArrayList used for the stack */
    private ArrayList<Integer> stack;

    /** default constructor */
    public StackArrayListBased() {
        stack = new ArrayList<Integer>();
    }  // end default constructor


    /** Tests if this stack has no elements.
     * @return true if this list has no elements;
     * false otherwise.
     */
    public boolean isEmpty() {
        return stack.isEmpty();
    }  // end isEmpty


    /** Adds an item to the top of a stack.
     *Postcondition: If insertion is successful, newItem is on the top
     * of the stack
     * @param newItem is the item to be added.
     * @throws some implementations may throw StackException when
     * newItem cannot be placed on the stack.
     */
    public void push(int newItem) throws StackException {
        stack.add(0, newItem);
    }  // end push

    /**
     * Removes all the items from the stack.
     * PostCondition: Stack is empty.
     */
    public void popAll() {
        stack.clear();
    }  // end popAll

    /**
     * Removes the top of a stack.
     * @return If the stack is not empty, the item that was added most
     * recently is removed from the stack and returned.
     * @throws StackException if the stack is empty.
     */
    public int pop() throws StackException {
        if (!isEmpty()) {
            return (int)stack.remove(0);
        }
        else {
            throw new StackException("StackException on " +
                    "pop: stack empty");
        }  // end if
    }  // end pop

    /**  Retrieves the top of a stack.
     * @return If the stack is not empty, the item that was added most
     * recently is returned. The stack is unchanged.
     * @throws StackException if the stack is empty.
     */
    public int peek() throws StackException {
        if (!isEmpty()) {
            return (int)stack.get(0);
        }
        else {
            throw new StackException("Stack exception on " +
                    "peek - stack empty");
        }  // end if
    }  
}    

StackInterface.java

package SinglePackage;

public interface StackInterface {

    /** Determines whether the stack is empty.
     * @return true if the stack is empty; false otherwise
     */
    public boolean isEmpty();
    
    /**
     * Removes all the items from the stack.
     * PostCondition: Stack is empty.
     */
    public void popAll();
    
    /** Adds an item to the top of a stack.     
     *Postcondition: If insertion is successful, newItem is on the top
     * of the stack
     * @param newItem is the item to be added.
     * @throws Some implementations may throw StackException when
     * newItem cannot be placed on the stack.
     */
    public void push(int newItem) throws StackException;

    /**
     * Removes the top of a stack.
     * @return If the stack is not empty, the item that was added most
     * recently is removed from the stack and returned.
     * @throws StackException if the stack is empty.
     */
    public int pop() throws StackException;
  
  
    /**  Retrieves the top of a stack.  
     * @return If the stack is not empty, the item that was added most
     * recently is returned. The stack is unchanged.
     * @throws StackException if the stack is empty.
     */
    public int peek() throws StackException;
 
    

} 

StackException.java

public class StackException 
             extends java.lang.RuntimeException {
  public StackException(String s) {
    super(s);
  }  // end constructor
}  

OutputFile:


Related Solutions

write a java program tht evaluates postfix expressions. args[0] = the output file the answer will...
write a java program tht evaluates postfix expressions. args[0] = the output file the answer will print to
Write a program that reads a file line by line, and reads each line’s tokens to...
Write a program that reads a file line by line, and reads each line’s tokens to create a Student object that gets inserted into an ArrayList that holds Student objects.  Each line from the file to read will contain two strings for first and last name, and three floats for three test grades.  After reading the file and filling the ArrayList with Student objects, sort the ArrayList and output the contents of the ArrayList so that the students with the highest average...
Postfix Evaluation (JAVA PROGRAMMING) Write class PostfixEva1uator that evaluates a postfix expression such as 6 2...
Postfix Evaluation (JAVA PROGRAMMING) Write class PostfixEva1uator that evaluates a postfix expression such as 6 2 + 5 * 8 4 / - The program should read a postfix expression consisting of single digits and operators into a StringBuilder, The program should read the expression and evaluate it (assume it's valid). The algorithm to evaluate a postfix expression is shown below. Use +, -, *, /, and ^. ^ is the exponent. Append a right parenthesis ') ' to the...
Write a program that converts prefix expressions to postfix and postfix expressions to prefix. (java) The...
Write a program that converts prefix expressions to postfix and postfix expressions to prefix. (java) The program for this project should consist of three classes. -The main class should create a GUI that allows the user to input an expression in either prefix or postfix and convert it to postfix or prefix, respectively. -The other class should contain the code to perform the conversions. --->The pseudocode for prefix to postfix, which requires two stacks, is shown below: tokenize the string...
Write a program in c that reads the content from the file and stores each line...
Write a program in c that reads the content from the file and stores each line in an int array in heap(using dynamic memory allocation). For example, let the file has elements following (we do not know the size of files, it could be above 100,000 and contents of the file and make sure to convert file elements to int): 10067 26789 6789 3467
(PYTHON) Write a program that does the following: reads each line from a txt file and...
(PYTHON) Write a program that does the following: reads each line from a txt file and convert it to lowercase counts the number of instances of: the characters 'a', 'e','i','o' and 'u' in the file creates a new file of file type .vowel_profile print outs lines in the file indicating the frequencies of each of these vowels Example input/output files: paragraph_from_wikipedia.txt (sample input) link: https://cs.nyu.edu/courses/fall19/CSCI-UA.0002-007/paragraph_from_wikipedia.txt paragraph_from_wikipedia.vowel_profile (sample output) link: https://cs.nyu.edu/courses/fall19/CSCI-UA.0002-007/paragraph_from_wikipedia.vowel_profile Please help!
IN JAVA PLZ follow all directions SHOW OUPUT! Write class PostfixEvaluator that evaluates a postfix expression...
IN JAVA PLZ follow all directions SHOW OUPUT! Write class PostfixEvaluator that evaluates a postfix expression such as 6 2 + 5 * 8 4 / - The program should read a postfix expression consisting of single digits and operators into a StringBuilder, The program should read the expression and evaluate it (assume it's valid). The algorithm to evaluate a postfix expression is shown below. Use +, -, *, /, and ^. ^ is the exponent. Append a right parenthesis...
C++ Data Structure Write a program to change following infix expressions to postfix expressions using a...
C++ Data Structure Write a program to change following infix expressions to postfix expressions using a stack a) D-B+C b) C*D+A*B c) (A*B)*C+D*F-C d) (A-4*(B-C)-D/E)*F
Write a program to convert a text-file containing expressions (one per line) into post-fix expressions outputted...
Write a program to convert a text-file containing expressions (one per line) into post-fix expressions outputted to a file of your choice using a stack with one space between operators and variables (one letter variables) and/or constants (one digit constants). IN PYTHON please
Write a program to convert a text-file containing expressions (one per line) into post-fix expressions outputted...
Write a program to convert a text-file containing expressions (one per line) into post-fix expressions outputted to a file of your choice using a stack with one space between operators and variables ( one letter variables) and/or constants (one digit constants).
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT