Question

In: Computer Science

Java please. A stack machine executes programs consisting of arithmetic commands that manipulate an internal stack....

Java please.

A stack machine executes programs consisting of arithmetic commands that manipulate an internal stack.

The stack is initially empty.

The commands are:

push N  ; push N onto the stack (N is any Double)

pop     ; removes top element from a stack

add     ; replace top two elements of the stack by their sum

mul     ; replace top two elements of the stack by their product

sub     ; replace top two elements of the stack by their difference: [a, b, ... ] => [a-b, ... ]

div     ; replace top two elements of the stack by their quotient: [a, b, ... ] => [a/b, ... ]

For example, the following program computes 23:

(push 1, push 2, mul, push 2, mul, push 2, mul)

The following types of exceptions are thrown by the stack machine:

stack empty

stack too short (not enough elements to complete the operation)

divide by 0

syntax error

Part 1

Implement a generic stack class for the stack machine:

class Stack<T> { ??? }

Notes

·You will need to implement the following methods: push, pop, top, clear, and toString.

·pop and top may throw EmptyStack exceptions

·How will you store the elements in the stack? List? Set?

Part 2

Implement your design using your solution for part 2.

Notes

·Executing arithmetic commands may throw ShortStack exceptions if there aren't at least two elements on the stack.

·div may throw a DivByZero exception. Restore the stack before throwing this exception.

·Consider making the execute method and stack in your StackMachine class static. Then, commands can make static references to the stack without needing to have an association to the stack machine.

·The execute method of StackMachine should have separate catch clauses for each type of exception. For now it just prints the exception but in the future we could potentially have different strategies for each type of exception caught.

·After the last command is execute the stack machine should print the stack.

·Before the first command is execute the stack machine should clear the stack.

Here is my code, but I am stuck here. Please help.

class Program{
   List<Command> commands;
   void excute() throws StackMachineException{
       for(Command c: commands)
           c.excute();
   }
}
class Add extends Command{
   void excute() throws StackMachineException{
      
   }
}
class Command{
  
  
}
class Stack<T>{
  
}
class StackMachineException{
  
  
}
public class StackMac {
   public Stack<Double> stack;
  
   void excute(Program p)
   {
      
   }
}

And here is the test code

public class StackMackTests {

        // f() = 5x^2 - 3
        public static void test0(Double x) {
                // create an empty program
                Program p = new Program();
                // add commands to p:
                p.add(new Push(3.0));
                p.add(new Push(x));
                p.add(new Push(x));
                p.add(new Push(5.0));
                p.add(new Mul());
                p.add(new Mul());
                p.add(new Sub());
                // now execute
                StackMachine.execute(p);
        }

        // f(x) = x^3 + 3x^2 - 2x + 1
        public static void test1(Double x) {
                // ???
        }

        public static void main(String[] args) {
                test1(2.0); // [17.0]
                test1(5.0); // [191.0]

                test0(2.0); // [17.0]
                test0(4.0); // [77]
        }

}

Solutions

Expert Solution

Note: Done accordingly. Please comment for any problem. Please Uprate. Thanks.

Your implementation was wrong. I have completed according to the specification.

Code:

TestStackMachine.java
public class TestStackMachine {
  
   public static void main(String[] args) {
StackMachine.execute("push 1, push 2, mul, push 11, mul, push 1, add");
   }
}

Stack.java

import java.util.EmptyStackException;

public class Stack<T> {

   private Node topPointer;
private int size;
  

/**
* Element node class structure.
*/
private class Node {
private T element;
private Node next;
}

public Stack()
{
size=0;
topPointer=null;
}

/**
* Push an element onto the stack.
*
* @param ele The new element.
* @return The stack instance, for chaining.
*/
public Stack<T> push(T info)
{
Node current = topPointer;
topPointer = new Node();
topPointer.element = info;
topPointer.next = current;
size++;
return this;
}

/**
* Pop an element off the stack.
*
* @return The popped element.
*/
public T pop()
{
   if(!isEmpty()){
       T info = topPointer.element;
       topPointer = topPointer.next;
       size--;
       return info;
   }else{
       throw new EmptyStackException();
   }
}
  
public T top()
{
   if(!isEmpty()){
T info = topPointer.element;
return info;
   }else{
       throw new EmptyStackException();
   }
}
  
public int size(){
   return size;
}

  
public boolean isEmpty(){
   if(size==0){
       return true;
   }else{
       return false;
   }
}
  
public void clear(){
   size=0;
topPointer=null;
}
  
public String toString(){
   String stackAsString="";
   Node current = topPointer;
   while(current!=null){
       stackAsString=stackAsString+current.element+" ";
       current=current.next;
   }
   return stackAsString;
}
}

StackMachine.java

import java.util.EmptyStackException;

public class StackMachine {
   static Stack<Double> stackData = new Stack<Double>();

   void push(double data) {
       stackData.push(data);
   }

   double pop() {
       double data;
       data = stackData.pop();
       return data;
   }

   void add() {
       if (stackData.size() >= 2) {
           double first=pop();
           double second=pop();
           push(first+second);
       } else {
           throw new NullPointerException("Not enough elements");
       }
   }

   void sub() {
       if (stackData.size() >= 2) {
           double first=pop();
           double second=pop();
           push(first-second);
       } else {
           throw new NullPointerException("Not enough elements");
       }
   }

   void multiply() {
       if (stackData.size() >= 2) {
           double first=pop();
           double second=pop();
           push(first*second);
       } else {
           throw new NullPointerException("Not enough elements");
       }
   }

   void divide() {
       if (stackData.size() >= 2) {
           double first=pop();
           double second=pop();
           if(second!=0){
               push(first/second);
           }else{
               push(second);
               push(first);
               throw new ArithmeticException("Divide by zero");
           }
       } else {
           throw new NullPointerException("Not enough elements");
       }
   }

   static void execute(String commands) {
       StackMachine obj=new StackMachine();
       String[] values = commands.split(",");
       try{
       for(String command: values){
           command=command.trim();
           command=command.toLowerCase();
           if(command.startsWith("push")){
               String[] commandValue=command.split(" ");
               obj.push(Double.parseDouble(commandValue[1]));
           }else if(command.startsWith("mul")){
               obj.multiply();
           }else if(command.startsWith("div")){
               obj.divide();
           }else if(command.startsWith("add")){
               obj.add();
           }else if(command.startsWith("sub")){
               obj.sub();
           }else{
               System.out.print("Invalid Command");
           }
       }
       }catch(ArithmeticException e){
           System.out.println(e.getMessage());
       }catch(NullPointerException e){
           System.out.println(e.getMessage());
       }catch(EmptyStackException e){
           System.out.println(e.getMessage());
       }catch(Exception e){
           System.out.println(e.getMessage());
       }
       System.out.print(stackData.toString());
   }
}

Output:


Related Solutions

Exercise 3: Stack Write a program in Java to manipulate a Stack List: 1. Create Stack...
Exercise 3: Stack Write a program in Java to manipulate a Stack List: 1. Create Stack List 2. Display the list 3. Create the function isEmply 4. Count the number of nodes 5. Insert a new node in the Stack List. 6. Delete the node in the Stack List. 7. Call all methods above in main method with the following data: Test Data : Input the number of nodes : 4 Input data for node 1 : 5 Input data...
please in java ! Assume you have a stack of integers. The stack contains same number...
please in java ! Assume you have a stack of integers. The stack contains same number of positive and negative integers. You want to organize it such that negative and positive integers alternate (+-+-.., or -+-+,..). A. Write a Java code that uses no more than two additional Stacks to solve the problem. Note: You do not need to write the code for Stacks, you are using a Stack from the library with a name ourStack and has the following...
JAVA PROGRAM (Make sure that programs are running. Please discuss, if there is any compilation or...
JAVA PROGRAM (Make sure that programs are running. Please discuss, if there is any compilation or run error.) Q. 1 Calculate the expression a)         x= 7.0 + (12 %3)*5 – 3;                    b)         x= 7 + (11 / 2)*5 + 3;            Q 2: Write a program that prompts the user to enter five test scores and then prints the average test score. (Assume that the test scores are decimal numbers.) Q 3. Write a program that prompts the capacity, in gallons,...
Ans In Java Please Homework 6-1 So far in this course, all of your programs have...
Ans In Java Please Homework 6-1 So far in this course, all of your programs have been written to be fully contained inside a single method named main. The main method is where Java begins execution of your program. In this assignment, you will coding other methods in addition to the main method. These additional methods will perform specific functions and, in most cases, return results. Write all your methods in a class named Homework6Methods.java Write a public static method...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT