Question

Reverse Polish (HP) Style Calculator - Part 3 The purpose of this assignment is to build...

Reverse Polish (HP) Style Calculator - Part 3

The purpose of this assignment is to build the business calculator using supporting files built in Topics 4 and 5.

Create a Java application file named RPN.java containing a main method by using the ForthStack.java and associated files from Topic 5.

The application should have one text box for numeric data entry, one text box for numeric display, one text box for error display, and buttons labeled "+", "-", "*", "/", "dup", "2dup", "clr", "pop" and "push."

The actions of the controls should be as follows.

The text box for numeric display should display the top element of the stack, or blank if the stack is empty.

The text box for numeric data entry should allow the user to type in a valid numeric value.

The text box for error display should display an error message from the previous operation (if any), or be blank if the last operation was successful.

The buttons labeled "+", "-", "*", "/", "dup", "2dup", "clr", and pop should invoke the corresponding methods in ForthStack; "pop" should remove and discard the top item on the stack, and "push" should push the numeric value in the numeric data entry box onto the stack and clear the numeric data entry box.

All button operations should update the display of the top of the stack.

The size of the stack used should be four, no more or less, in order to standardize testing.

After thoroughly testing the program, submit the AbstractStack.java, ArrayStack.java, Forth.java, ForthStack.java, TestForthStack.java, and RPN.java files to the instructor.

Reverse Polish (HP) Style Calculator - Part 2 ***COMPLETED*** Program Below

Implement a pure abstract stack class named AbstractStack that has no implementation. It will not have a private array of double, because that is an implementation detail of ArrayStack that would not be found in other implementations such as LinkedStack. Nor will it have the constructor public AbstractClass(int size), or methods public double peek(int n) or public int count(), since these methods are convenience features that are easily implemented for ArrayStack, but not other implementations of stack.

Include the method public double peek(), and add the method public void clear(), resulting in the following abstract methods.

public abstract void push(double item) – Standard stack action; Throws an exception if the stack is full.

public abstract double pop() – Standard stack action; Throws an exception if the stack is empty.

public abstract boolean isEmpty() – Returns true if the stack is empty and false otherwise.

public abstract double peek() – returns the value of the item located at the specified position on the stack; throws an exception if the array bounds are exceeded or if a nonexistent element is requested.

public abstract void clear() – empties the stack if it is not already empty.

Do not specify a constructor. Depend on the default constructor.

Modify the existing ArrayStack.java file to include the phrase "extends AbstractStack."

Add an implementation for the methods void clear() and double peek(), which overloads the existing double peek(int n). Provide a default constructor that creates an array that will hold three elements.

public ArrayClass(int size) - constructor that creates an ArrayClass instance containing an array of the specified size. Remember that in Java, arrays are indexed from 0!

public push(double item) – standard stack action; throws an exception if the array bounds are exceeded.

public double pop() – standard stack action; throws an exception if the array bounds are exceeded.

public boolean isEmpty() – returns true if the stack is empty and false otherwise.

public double peek(int n) – returns the value of the item located at the specified position on the stack; throws an exception if the array bounds are exceeded or if a nonexistent element is requested; peek(0) will return the top element of the stack.

public int count() - returns the number of items currently pushed onto the stack.

Modify the existing TestArrayStack.java file to include tests for void clear() and double peek(). Note that it is easiest to do "incremental testing" in which you code a little then test a little.

Create an interface with additional methods.

Create a new file called Forth.java. Make this a public interface file. Add the following methods to the interface.

public add() – pops two values from the stack, adds them together, and pushes the result back onto the stack. Throws an exception if there are not at least 2 items on the stack.

public sub() – pops two values from the stack, subtracts the second number popped from the first number popped, and pushes the result back onto the stack. Throws an exception if there are not at least 2 items on the stack.

public mult() – pops two values from the stack, multiplies them together, and pushes the result back onto the stack. Throws an exception if there are not at least 2 items on the stack.

public div() – pops two values from the stack, divides the second number popped by the first number popped, and pushes the result back onto the stack. Throws an exception if there are not at least 2 items on the stack.

public dup() – peeks at the top value on the stack and pushes a copy of that value onto the stack. Throws an exception if the stack is empty or full.

public twoDup() – peeks at the top two values on the stack and pushes a copy of both values onto the stack (in the same order). Throws an exception if the stack does not have at least 2 items or room for 2 additional items.

Create another file called ForthStack.java. Make this file extend ArrayStack and implement Forth. Code concrete implementations of each of the methods in the interface.

Test by making a copy of the file TestArrayStack.java and name it TestForth. Change the name of the class inside the file. Add tests for add, sub, mult, div, dup, and twoDup.

After thoroughly testing the program, submit the AbstractStack.java, ArrayStack.java, Forth.java, ForthStack.java, and TestForthStack.java files

package chegg.june;

public class Chegg357 {
   
}

abstract class AbstractStack {
    public abstract void push(double item);
    public abstract double pop();
    public abstract boolean isEmpty();
    public abstract double peek();
    public abstract void clear()
}

class ArrayStack extends AbstractStack{
   
    private double[] array;
    private int size;
    private int num;
    public ArrayStack(int a){
        array = new double[a];
        size = a;
        num = 0;
    }
    public void push(double a){
    if (num < size){
    array[num] = a;
    num++;
    }
    else {
    System.out.println("Stack is full");
    }

    }
    public void pop(){
    if (num > 0){
    num--;
    return array[num];
    }
    else {
    System.out.println("Stack is empty");
    return -1;
    }

    }
    public void isEmpty(){
    return (num == 0);
    }
    public void peek(int n){
    try {
    if (num > 0){
    if (n < 0 || n >= num)
    return -1
    else
    return array[num-1-n];
    }
    else {
    System.out.println("Stack is empty");
    return -1;
    }
    }
    catch(ArrayindexOutOfBoundsException e ){
    e.printStackTrace();
    }
    }
    public int count(){
    return num;
    }

    @Override
    public double peek() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void clear() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}

Reverse Polish (HP) Style Calculator - Part 1 ***COMPLETED*** Program Below

The purpose of this assignment is to use array as stack to begin constructing a business calculator.

Throughout the remainder of the course, you will complete a series of programming functions that will allow you to develop an emulator for a Hewlett-Packard business calculator that uses the Reverse Polish Notation (RPN) discussed in the Topic Materials.

Reverse Polish Notation is also the basis for a computer programming language for embedded applications called Forth, which you read about in the Topic Materials. As part of this project, you will develop a simplified Forth interpreter.

The heart of a RPN calculator is a data structure called a stack. Review the Topic Materials video tutorials and textbook sections 14.3 and 14.5 and study the examples related to stack prior to completing the programming steps below.

Implement a stack class named ArrayStack that "has-a" private array of double.

Implement the methods:

public ArrayClass(int size) - constructor that creates an ArrayClass instance containing an array of the specified size. Remember that in Java, arrays are indexed from 0!

public push(double item) – standard stack action; throws an exception if the array bounds are exceeded.

public double pop() – standard stack action; throws an exception if the array bounds are exceeded.

public boolean isEmpty() – returns true if the stack is empty, and false otherwise.

public double peek(int n) – returns the value of the item located at the specified position on the stack; throws an exception if the array bounds are exceeded or if a nonexistent element is requested; peek(0) will return the top element of the stack.

public int count() - returns the number of items currently pushed onto the stack.

Implement a console application class named TestArrayStack containing a main method that tests each of the above methods of the ArrayStack by creating an instance of ArrayStack and calling each of the methods to test that each functions normally as described and fails with exceptions as described.

When a failure occurs, print a descriptive error message to the console and stop.

Keep adding tests and correcting bugs until all tests pass and you have "covered" all aspects of the specification. When this happens, print out "SUCCESS" and stop.

Note: The details of the methods specified above may be somewhat different from the discussion in the text and the videos. You will have to think about adapting the ideas in these sources, as is usual in programming. Available examples are only "good approximations" of what you need to do. You need to add the creative energy to make the adaptations.

Use the debugging features of Eclipse to step though the program to find and correct bugs.

After thoroughly testing the program, submit the ArrayStack.java and TestArrayStack.java files to the instructor.

class ArrayStack {

private double[] array;
private int size;
private int num;

public ArrayStack(int a){
array = new double[a];
size = a;
num = 0;
}
public void push(double a){
if (num < size){
array[num] = a;
num++;
}
else {
System.out.println("Stack is full");
}
  
}
public void pop(){
if (num > 0){
num--;
return array[num];
}
else {
System.out.println("Stack is empty");
return -1;
}
  
}
public void isEmpty(){
return (num == 0);
}
public void peek(int n){
try {
if (num > 0){
if (n < 0 || n >= num)
return -1
else
return array[num-1-n];
}
else {
System.out.println("Stack is empty");
return -1;
}
}
catch(ArrayindexOutOfBoundsException e ){
e.printStackTrace();
}
}
public int count(){
return num;
}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Ans:-

import java.util.*;
public class RPN {
/**
* Computes the outcome of a given expression in Reverse Polish Notation
*
* @param expr the expression to compute
*/
public static void compute(String expr) throws
ArithmeticException,
EmptyStackException {
Stack<Double> stack = new Stack<>();
System.out.println(expr);
System.out.println("Input\tOperation\tStack after");
for (String token : expr.split("\\s+")) {
System.out.print(token + "\t");
switch (token) {
case "+":
System.out.print("Operate\t\t");
stack.push(stack.pop() + stack.pop());
break;
case "-":
System.out.print("Operate\t\t");
stack.push(-stack.pop() + stack.pop());
break;
case "*":
System.out.print("Operate\t\t");
stack.push(stack.pop() * stack.pop());
break;
case "/":
System.out.print("Operate\t\t");
double divisor = stack.pop();
stack.push(stack.pop() / divisor);
break;
case "^":
System.out.print("Operate\t\t");
double exponent = stack.pop();
stack.push(Math.pow(stack.pop(), exponent));
break;
default:
System.out.print("Push\t\t");
stack.push(Double.parseDouble(token));
break;
}
System.out.println(stack);
}
System.out.println("Final Answer: " + stack.pop());
}
/**
* Runs the calculation for the RPN expression in args[0].
*/
public static void main(String[] args) {
try {
compute(args[0]);
} catch (Exception err) {
System.out.println(err.getMessage());
}
}
}

NOTE:-

If you have any doubts then comment below i am very happy to solve your doubts

Thank you

Add a comment
Know the answer?
Add Answer to:
Reverse Polish (HP) Style Calculator - Part 3 The purpose of this assignment is to build...
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
  • Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an ...

    Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an array. Implement all methods in ArrayStack class using resizable array strategy, i.e. usedoubleArray() Must throw StackException during exception events in methods:    peek(), pop(), ArrayStack(int initialCapacity) Do not change or add data fields Do not add new methods */ import java.util.Arrays; public class Arraystack«Т> implements Stack!nterface«T> private TI stack;// Array of stack entries private int topIndex; /7 Index of top entry private static...

  • Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored...

    Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an array. Implement all methods in ArrayStack class using resizable array strategy, i.e. usedoubleArray() Must throw StackException during exception events in methods:    peek(), pop(), ArrayStack(int initialCapacity) Do not change or add data fields Do not add new methods */ import java.util.Arrays; public class Arraystack«Т> implements Stack!nterface«T> private TI stack;// Array of stack entries private int topIndex; /7 Index of top entry private...

  • I need to implement a stack array but the top of the stack has to be...

    I need to implement a stack array but the top of the stack has to be Initialize as the index of the last location in the array.    //Array implementation of stacks.    import java.util.Arrays;       public class ArrayStack implements Stack {        //Declare a class constant called DEFAULT_STACK_SIZE with the value 10.           private static final int DEFAULT_STACK_SIZE = 10;           /* Declare two instance variables:            1. An integer called...

  • Java - data structures Suppose that in the array-based stack, the array doubles in size after...

    Java - data structures Suppose that in the array-based stack, the array doubles in size after multiple push operations. But later on, fewer than half of the array’s locations might actually be used by the stack due to pop operations. Revise the implementation so that its array also can shrink in size as objects are removed from the stack. Accomplishing this task will require two new private methods, as follows: The first new method checks whether we should reduce the...

  • In Java. What would the methods of this class look like? StackADT.java public interface StackADT<T> {...

    In Java. What would the methods of this class look like? StackADT.java public interface StackADT<T> { /** Adds one element to the top of this stack. * @param element element to be pushed onto stack */ public void push (T element);    /** Removes and returns the top element from this stack. * @return T element removed from the top of the stack */ public T pop(); /** Returns without removing the top element of this stack. * @return T...

  • In addition to the base files, three additional files are attached: EmptyCollectionException.java, LinearNode.java, and StackADT.java. These...

    In addition to the base files, three additional files are attached: EmptyCollectionException.java, LinearNode.java, and StackADT.java. These files will need to be added to your Java project. They provide data structure functionality that you will build over. It is suggested that you test if these files have been properly added to your project by confirming that Base_A05Q1.java compiles correctly. Complete the implementation of the ArrayStack class. Specifically, complete the implementations of the isEmpty, size, and toString methods. See Base_A05Q1.java for a...

  • Suppose we decide to add a new operation to our Stack ADT called sizeIs, which returns...

    Suppose we decide to add a new operation to our Stack ADT called sizeIs, which returns a value of primitive type int equal to the number of items on the stack. The method signature for sizeIS is public int sizeIs() a.) Write the code for sizeIs for the ArrayStack class b.) Write the code for sizeIs for the LinkedStack class (do not add any instance variables to the class; each time sizeIs is called you must "walk" through the stack...

  • how do I change my code to generic form *********************************************************************** public class UnboundedStackQueue { //question#3 }...

    how do I change my code to generic form *********************************************************************** public class UnboundedStackQueue { //question#3 } class Stack { Node head; int size; Stack() //default constructor { this.head=null; this.size=0; } //Input = data //Output = void (just adds value to list) // method pushes elements on stack // time: O(1) // space: O(1) public void push(int data) { Node node=new Node(data); node.next=head; head=node; size++; } //Input = none //Output = top of stack // method pops value from top of...

  • Currently, I'm getting this as my output: "Exception in thread "main" java.lang.NullPointerException    at InfixExpression.execute(InfixExpression.java:98)   ...

    Currently, I'm getting this as my output: "Exception in thread "main" java.lang.NullPointerException    at InfixExpression.execute(InfixExpression.java:98)    at InfixExpression.Evaluate(InfixExpression.java:65)    at InfixExpression.setWholeExpr(InfixExpression.java:24)    at InfixExpression.<init>(InfixExpression.java:17)    at Main.testHW1(Main.java:17)    at Main.main(Main.java:6)" I need to get this as my output: "Testing InfixExpression: When passing null, the String and double = Infix String: , result: 0.0 When passing a valid String, the String and double = Infix String: ( 234.5 * ( 5.6 + 7.0 ) ) / 100.2, result: 29.488023952095805 ..." I...

  • Description: \\ implement in Java Based on Chapter 6, programming project 1 Hewlett-Packard has a tradition...

    Description: \\ implement in Java Based on Chapter 6, programming project 1 Hewlett-Packard has a tradition of creating stack-based calculators. Rather than using standard algebraic notation ( 1 + 1 = ), the user would enter the values, then the operator. The calculator had an “enter” key to push each value onto a stack, then pop the stack when an operation key (e.g. “+” or “-”) was pressed. Assignment: Create a Calculator class that implements the provided StackCalculator interface Requirement Constructor: + Calculator()   ...

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