Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Java 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

Java

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 (http://www.geeksforgeeks.org/java-util-arrays-copyof-java-examples/)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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored 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

Probabilistic Databases

Authors: Dan Suciu, Dan Olteanu, Christopher Re, Christoph Koch

1st Edition

3031007514, 978-3031007514

More Books

Students also viewed these Databases questions

Question

What is a new-venture team?

Answered: 1 week ago