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
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
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
Lab 7. Boolean Expressions a) Write a program that evaluates the following expressions. Assign reasonable values...
Lab 7. Boolean Expressions a) Write a program that evaluates the following expressions. Assign reasonable values to the variables. Print the results. a<b≥c , √a−7 b2 ≠c , d∨e∧f , a<b∨¬d ∧means and, ∨means inclusive or, ¬ means not. b) Write a program that asks a user whether he or she wants to become a Java programmer and determines if the user typed “yes” (Print true if yes and false otherwise.) Don't use the if statement here
Write a simple text-formating.cpp file that reads (asks for then reads) a text file and produces...
Write a simple text-formating.cpp file that reads (asks for then reads) a text file and produces another text file in Which blank lines are removed, multiple blanks are replaced with a single blank, and no lines are longer than some given length (let say 80). Put as many words as possible on the same line (as close as possible to 80 characters). You will have to break some lines of the given file, but do not break any words or...
Write a program that reads two strings from an input file (The first line is X,...
Write a program that reads two strings from an input file (The first line is X, the second line is Y), compute the longest common subsequence length AND the resulting string. You will need to write 2 methods 1) return LCS length in iterative function // return the length of LCS. L is the 2D matrix, X, Y are the input strings, m=|X|, n=|Y| int lcs_it(int **C, string X, string Y, int m, int n ) 2) return LCS resulting...
C++ Write a program that prompts for a file name and then reads the file to...
C++ Write a program that prompts for a file name and then reads the file to check for balanced curly braces, {; parentheses, (); and square brackets, []. Use a stack to store the most recent unmatched left symbol. The program should ignore any character that is not a parenthesis, curly brace, or square bracket. Note that proper nesting is required. For instance, [a(b]c) is invalid. Display the line number the error occurred on. These are a few of the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT