Question

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 topOfStackIndex
           2. A reference variable of type array of objects.
       */
      
       private int topOfStackIndex;
       private Object[] stack;
      
       /* Write the one parameter constructor.
       The parameter indicates the size of the stack
       (i.e. the size of the array that represents that stack.)
       Be sure to create the array and initialize each element to null.
       Initialize the top of stack to be the index of the last location in the array.
       */
          
       public ArrayStack(int size) {
           this.topOfStackIndex = (size - 1);
          
           this.stack = new Object[size];
          
           for(int i = 0; i < size - 1; i++) {
               this.stack[i] = null;
           }
       }
  
       /* Write the default (no parameter) constructor.
       Initialize the instance variables by invoking the one parameter constructor
       you just completed. Set the size of the stack to DEFAULT_STACK_SIZE.
       */
      
       public ArrayStack() {
           this(DEFAULT_STACK_SIZE);
}
  
       /* Write the method to implement the push operation.
       Be sure to first check to see if the stack is full.
       If the stack is full invoke the method expandCapacity to 'grow' the stack.
       */
      
       public boolean isFull(){
           return topOfStackIndex == this.stack.length;
          
       }
      
       public void push(Object data) {
           if (isFull()) {
               expandCapacity();
           }
           else {
               ++topOfStackIndex;
               stack[topOfStackIndex] = data;
           }
       }
  
       /* Write the method to implement peek operation.
       It should throw an EmptyCollectionException if the stack is empty.
       A stub method is provided for you.
       A stub method is a method that is a temporary substitute for yet
       to be developed code.
       The header is correct. The body has no funcitonality except that
       it will satisfy the compiler.
       */

       public Object peek() throws EmptyCollectionException {
           if(!isEmpty()) {
               return stack[topOfStackIndex];
           }
           else {
               throw new EmptyCollectionException ("The stack is empty");
           }
       }

       /* Write the pop operation.
       Like the peek operation, pop should throw an EmptyCollectionException if the stack is empty.
       Be sure to set the position from where the element was removed to null.
       Again, a stub method is provide for you.
       */
      
       public Object pop() throws EmptyCollectionException {
           if(!isEmpty()) {
               this.stack[topOfStackIndex] = null;
               topOfStackIndex++;
               Object result = this.stack[topOfStackIndex];
               return result;
           }
           else {
               throw new EmptyCollectionException ("The stack is empty");
           }
       }

       /* Write the method isEmpty.
       It returns true if the stack is empty and false otherwise.
       */
     
       public boolean isEmpty() {
           return topOfStackIndex == -1;
       }

       /* Write the method size.
       It returns an integer representing the number of items on the stack.
       */

       public int size() {
           int count = 0;
           for(int i = 0; i < stack.length - 1; i++) {
               if(stack[i] != null) {
                   count++;
               }
           }
           return count;
       }

       //This method has been completed for you.
       @Override
       public String toString() {
           return(this.toString());
       }
  
       /* This method is called from the push method when the stack is full.
       It should keep the current stack contents and double the size of the stack.
       Hint: Look at the methods in the Java Arrays class to help you here.
       */
      
       public void expandCapacity() {
           //Object[] temp = new Object[stack.length * 2];
           Object[] temp;
           temp = Arrays.copyOf(stack, (stack.length * 2));
           stack = temp;
       }

       /* This method is used for testing purposes.
       It is complete. Do not modify this method.
       */
      
       public int whatIsTopOfStack() {
           return topOfStackIndex;
       }
   }

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

Code

import java.util.Arrays;

public class ArrayStack implements Stack {

private static final int DEFAULT_STACK_SIZE = 10;

private int topOfStackIndex;
private Object[] stack;

public ArrayStack(int size) {
this.topOfStackIndex = (size - 1);

this.stack = new Object[size];

for(int i = 0; i < size - 1; i++) {
this.stack[i] = null;
}
}
public ArrayStack() {
this(DEFAULT_STACK_SIZE);
}
public boolean isFull(){
return topOfStackIndex == this.stack.length;

}

public void push(Object data) {
if (isFull()) {
expandCapacity();
}
else {
++topOfStackIndex;
stack[topOfStackIndex] = data;
}
}

public Object peek() throws EmptyCollectionException {
if(!isEmpty()) {
return stack[topOfStackIndex];
}
else {
throw new EmptyCollectionException ();
}
}

public Object pop() throws EmptyCollectionException {
if(!isEmpty()) {
this.stack[topOfStackIndex] = null;
topOfStackIndex++;
Object result = this.stack[topOfStackIndex];
return result;
}
else {
throw new EmptyCollectionException ();
}
}

public boolean isEmpty() {
return topOfStackIndex == -1;
}

public int size() {
int count = 0;
for(int i = 0; i < stack.length - 1; i++) {
if(stack[i] != null) {
count++;
}
}
return count;
}

@Override
public String toString() {
return(this.toString());
}

public void expandCapacity() {
  
Object[] temp;
temp = Arrays.copyOf(stack, (stack.length * 2));
stack = temp;
}

public int whatIsTopOfStack() {
return topOfStackIndex;
}
}

//Add Stack class

//Create class EmptyCollectionException (Opens the new class wizard to create the type.)

//Package: (default package)
//public class EmptyCollectionException extends Exception {
//}

Add a comment
Know the answer?
Add Answer to:
I need to implement a stack array but the top of the stack has to be...
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 - 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...

  • What is wrong with my code, when I pass in 4 It will not run, without...

    What is wrong with my code, when I pass in 4 It will not run, without the 4 it will run, but throw and error. I am getting the error   required: no arguments found: int reason: actual and formal argument lists differ in length where T is a type-variable: T extends Object declared in class LinkedDropOutStack public class Help { /** * Program entry point for drop-out stack testing. * @param args Argument list. */ public static void main(String[] args)...

  • I need to implement raw array Stack for create empty stack, isEmpty, isFull, push, pop, and...

    I need to implement raw array Stack for create empty stack, isEmpty, isFull, push, pop, and size using below pseudo code. I need two classes with stack pseudo code implementation and the main method to demonstrate the correct working of each operation. pseudo code StackADT (using raw array) class StackADT { int top int items[] int max StackADT(int n) Initialize array to n capacity top = 0 max = n boolean isEmpty() if array has no elements return true else...

  • 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...

  • I have a java project that I need help trying to finish. I have most of it completed but the issue I am running into is adding numbers with different lengths. Project requirements: . Use a Stack ADT w...

    I have a java project that I need help trying to finish. I have most of it completed but the issue I am running into is adding numbers with different lengths. Project requirements: . Use a Stack ADT with the implementation of your choice (Array or Link), it should not make a difference 2.Read two “integer” numbers from the user. Hint: You don’t need to use an int type when you read, it may be easier to parse the input...

  • 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...

  • JAVA Lab Create a class called ArrayBasedStack. Declare the following variables: • data: references an array...

    JAVA Lab Create a class called ArrayBasedStack. Declare the following variables: • data: references an array storing elements in the list • topOfStack: an int value representing the location of the stack top in the array • INITIAL_CAPACITY: the default capacity of the stack public class ArrayBasedStack <E> { private E[] data; private int topOfStack; private static final int INITIAL_CAPACITY = 5; } Add a constructor that will initialize the stack with a user-defined initial capacity. The top of the...

  • 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...

  • There is a data structure called a drop-out stack that behaves like a stack in every...

    There is a data structure called a drop-out stack that behaves like a stack in every respect except that if the stack size is n, then when the n+1element is pushed, the bottom element is lost. Implement a drop-out stack using links, by modifying the LinkedStack code. (size, n, is provided by the constructor. Request: Please create a separate driver class, in a different file, that tests on different types of entries and show result of the tests done on...

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