Answered step by step
Verified Expert Solution
Link Copied!

Question

...
1 Approved Answer

Goal: Using a Stack simulate a reversepolish notation (RPN) calculator. A description of an RPN calculator works is given at the end ofthis page (right

Goal: Using a Stack simulate a reversepolish notation (RPN) calculator.
A description of an RPN calculator works is given at the end ofthis page (right after the sample test)

Note: No need to implement Stack fromscratch. Instead use the Java built-in Stack class for thisassignment.

How does a polish calculator work?

To add 2 and 5, you should type: 2 5 +

and the corresponding method should be:

public double add() {    return stack.push(stack.pop() + stack.pop());}

SAMPLE TEST CASES ARE GIVEN IN THE TA TESTFILE

Test 1: 8 2 / ( this prints 4)

Test 2: 9 3 / (this prints 3)

Test 3: 2 3 ^ (this prints 8)

Test 4: 8 log (this prints 2.08)

Test 5: 0 cos ( this prints 1)

Test 6: 8 log 2 log / (this prints 3)

Test 7: 2 3 4 + * 0.5 / (this prints 28)

Test 8: 3 2 ^ 4 2 ^ + sqrt (this prints 5)

Code Provided

CalculatorException.java

public class CalculatorException extends Exception {    /**     Create a private instance variable:        name: mesg        type: String     */        /**     Create a Constructor and a Default Constructor     for an input of a String with the default value     being an empty String.     */        /**        Example:            mesg: "Some Message"            output: CalculatorException: Some Message    */    public String toString() {            }}

RPNCalculator.java

import java.io.File;import java.io.FileNotFoundException;import java.io.IOError;import java.util.Scanner;import java.util.Stack;import java.lang.Math;import java.util.regex.Pattern;public class RPNCalculator {    private Stack stack;    private Pattern identToken;    private Pattern binopToken;    public RPNCalculator() {        // Initialize stack to be an empty Stack to hold double data values                // these are for processing text input        identToken = Pattern.compile("p{Alpha}+");        binopToken = Pattern.compile("+|*|-|/|^");    }    /** Push the element x into the stack(x should be on the top of the stack), and return x. */    public double enter(double x) {            }    public double add() {        return stack.push(stack.pop() + stack.pop());    }    /**        Example: calculate 5 - 2 = ?, push the output to stack, and return the output            Input (you should enter): 5 2 -            Output: 3.0     */    public double subtract() {            }    /**        Example: calculate 2 * 5 = ?, push the output to stack, and return the output            Input (you should enter): 2 5 *            Output: 10.0     */    public double multiply() {            }    /**        Example: calculate 8 / 2 = ?, push the output to stack, and return the output            Input (you should enter): 8 2 /            Output: 4.0     */    public double divide() {            }    /**        Example: calculate 2^3 = ?, push the output to stack, and return the output            Input (you should enter): 2 3 ^            Output: 8.0            Hint: Use Math.pow()    */    public double power() {            }    /**        Example: calculate e^2 = ?, push the output to stack, and return the output            Input (you should enter): 2 exp            Output: 7.389056099            Hint: Use Math.exp()    */    public double exp() {            }    /**        Example: calculate ln e = ?, push the output to stack, and return the output            Input (you should enter): e log            Output: 1            Hint: Use Math.log()    */    public double log() {            }    /**        Example: calculate sin(0) = ?, push the output to stack, and return the output            Input (you should enter): 0 sin            Output: 0            Hint: Use Math.sin()    */    public double sin() {            }    /**        Example: calculate cos(0) = ?, push the output to stack, and return the output            Input (you should enter): 0 cos            Output: 1            Hint: Use Math.cos()    */    public double cos() {            }    /**        Example: calculate ?100 = ?, push the output to stack, and return the output            Input (you should enter): 100 sqrt            Output: 10            Hint: Use Math.sqrt()    */    public double sqrt() {            }    /** Return the element at the top of the stack and remove it. */    public double pop() {            }    /** Clear your stack, expect your stack to be empty */    public void clear() {            }    public void processLine(String line) throws CalculatorException {        Scanner linescan = new Scanner(line);        while ( linescan.hasNext() ) {            if ( linescan.hasNextDouble() ) {                enter(linescan.nextDouble());            }            else if ( linescan.hasNext(binopToken) )            {                String binop = linescan.next(binopToken);                switch ( binop ) {                    case "+": add(); break;                    case "-": subtract(); break;                    case "*": multiply(); break;                    case "/": divide(); break;                    case "^": power(); break;                    default:                        /**                            Example:                                the variable binop: x                                throw a CalculatorException with error message format: Unknown operation: x                         */                                        }            }            else if ( linescan.hasNext(identToken) )            {                String func = linescan.next(identToken);                switch ( func ) {                    case "exp": exp(); break;                    case "log": log(); break;                    case "sin": sin(); break;                    case "cos": cos(); break;                    case "sqrt": sqrt(); break;                    case "inspect":                        System.out.println("Stack: " + stack); break;                    case "end": case "break": case "stop": case "quit":                        System.exit(0); break;                    default:                        /**                         Example:                            the variable func: x                            throw a CalculatorException with error message format: Unknown function: x                         */                                        }            }            else                /**                     Example:                        parameter line: x                        throw a CalculatorException with error message format: Cannot process "x"                */                        }    }    /**        Format:            Enter: 8 2 /            Output: 4            Enter: 1 5 +            Output: 6     */    public static void main(String[] args) {        Scanner scnr = null;        if ( args.length > 0 ) {            try {                scnr = new Scanner(new File(args[0]));            } catch (FileNotFoundException e) {                System.out.println("Could not find file "" + args[0] + """);                System.out.println("Exception: " + e);                System.exit(1);            } catch (IOError e) {                System.out.println("IOException opening file "" + args[0] + """);                System.out.println("Exception: " + e);                System.exit(1);            }        } else {            scnr = new Scanner(System.in);            // Some helpful instructions            System.out.println("RPN calculator");            System.out.println("Separate inputs by spaces");            System.out.println("Enter "stop", "quit", "end" to end program" +                    " and "inspect" to see the state of the stack");            System.out.println("Operators: +, -, *, /, ^");            System.out.println("Functions: sin, cos, exp, log, sqrt");        }        RPNCalculator calc = new RPNCalculator();        while ( scnr.hasNextLine() ) {            // process each line separately            try {                String line = scnr.nextLine();                System.out.println("Processing line: " + line);                calc.processLine(line);                System.out.println("Result is " + calc.pop());            }            catch (CalculatorException e) {                System.out.println("" + e);            }            catch (Exception e) {                System.out.println("Exception: " + e);            }            calc.clear();        }    }}

Test Provided

CalculatorExceptionTest.java

import org.junit.Test;import static org.junit.Assert.*;public class CalculatorExceptionTest {    @Test    public void testDefaultConstructor() {        CalculatorException e = new CalculatorException();        assertEquals("CalculatorException: ", e.toString());    }    @Test    public void testConstructor() {        CalculatorException e = new CalculatorException("Error");        assertEquals("CalculatorException: Error", e.toString());    }}

RPNCalculatorTest.java

import org.junit.Test;import static org.junit.Assert.*;public class RPNCalculatorTest {    RPNCalculator calc = new RPNCalculator();    @Test    public void testEnter() {        assertEquals(3.0, calc.enter(3.0), 0.0001);    }    @Test    public void testPop() {        calc.enter(3.0);        assertEquals(3.0, calc.pop(), 0.0001);    }    @Test    public void testDiv() throws CalculatorException {        calc.processLine("8 2 /");        assertEquals(4.0,calc.pop(), 0.0001);    }    @Test    public void testPow() throws CalculatorException {        calc.processLine("4 3 ^");        assertEquals(64,calc.pop(), 0.0001);    }    @Test    public void testLog2() throws CalculatorException {        calc.processLine("8 log");        assertEquals(2.0794,calc.pop(), 0.0001);    }    @Test    public void testCos() throws CalculatorException {        calc.processLine("0 cos");        assertEquals(1, calc.pop(), 0.0001);    }    @Test    public void testLogLong() throws CalculatorException {        calc.processLine("8 log 2 log /");        assertEquals(3,calc.pop(), 0.0001);    }}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access with AI-Powered Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Income Tax Fundamentals 2013

Authors: Gerald E. Whittenburg, Martha Altus Buller, Steven L Gill

31st Edition

9781285586618

Students also viewed these Programming questions

Question

=+for the shareholder of the acquiring company?

Answered: 1 week ago

Question

=+for the shareholder of the acquired company?

Answered: 1 week ago

Question

=+for the acquired company?

Answered: 1 week ago