Question: I need to complete the StackArray class! Implement an array-based stack as described in Section 16.3 of your textbook. Use the code below as a

I need to complete the StackArray class!

Implement an array-based stack as described in Section 16.3 of your textbook. Use the code below as a guide and the runner class below for testing. Complete the code by writing the body of the push and pop methods:

When you have filled the array by pushing elements onto the stack, you must double the size of the array dynamically Hint: consider using the pre-defined static method Arrays.copyOf with a newLength of 2*item.length

Throw a NoSuchElementException if the pop method is invoked on an empty stack

import java.util.NoSuchElementException; public class StackArray { private Object[] item; // The array where elements are stored private int open = 0; // The index of the first empty location in the stack private static final int INITIAL_SIZE = 2; // The initial number of item locations in the stack /** Constructs an empty stack. */ public StackArray() { item = new Object[INITIAL_SIZE]; } public void push(Object element) { // put your code here } public Object pop() throws NoSuchElementException { // put your code here } public boolean isEmpty() { return open == 0; } public String toString() { if (open == 0) { return "[]"; } String temp = "[" + item[0]; int i = 1; while (i < open) { temp = temp + ", " + item[i]; i = i + 1; } temp = temp + "]"; return temp; } }

You can test your StackArray with the following test class:

public class StackArrayRunner { public static void main(String[] args) { StackArray sa = new StackArray(); sa.push("a"); sa.push("b"); sa.push("c"); sa.push("d"); sa.push("e"); try { System.out.println(sa); System.out.println(sa.pop()); System.out.println(sa); System.out.println(sa.pop()); System.out.println(sa); System.out.println(sa.pop()); System.out.println(sa); System.out.println(sa.pop()); System.out.println(sa); System.out.println(sa.pop()); System.out.println(sa); System.out.println(sa.pop()); } catch (Exception e) { e.printStackTrace(); } } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!