Question: Please add the necessary code to ArrayStack.java (listed as ADD CODE HERE). The code for BalanceChecker.java and StackInterface.java is also provided for the whole program.
Please add the necessary code to ArrayStack.java (listed as "ADD CODE HERE"). The code for BalanceChecker.java and StackInterface.java is also provided for the whole program.
ArrayStack.java
import java.util.Arrays; import java.util.EmptyStackException;
public class ArrayStack
public ArrayStack() { this(DEFAULT_CAPACITY); }
public ArrayStack(int initialCapacity) { checkCapacity(initialCapacity);
@SuppressWarnings("unchecked") T[] tempStack = (T[])new Object[initialCapacity]; entries = tempStack; topIndex = -1; }
@Override public T pop() { if(isEmpty()) { throw new EmptyStackException(); } else { T top = entries[topIndex]; entries[topIndex] = null; topIndex--; return top; } }
@Override public void push(T newEntry) { ensureCapacity(); entries[topIndex + 1] = newEntry; topIndex ++; }
@Override public T peek() { if(isEmpty()) { throw new EmptyStackException(); } else { return entries[topIndex]; } }
@Override public boolean isEmpty() { // ADD CODE HERE return true; }
@Override public void clear() { // ADD CODE HERE }
private void ensureCapacity() { if(topIndex == entries.length - 1) { int newLength = 2 * entries.length; checkCapacity(newLength); entries = Arrays.copyOf(entries, newLength); } }
private void checkCapacity(int capacity) { if (capacity > MAX_CAPACITY) { throw new IllegalStateException("Capacity too large"); } } }
BalanceChecker.java
public class BalanceChecker { public static boolean checkBalance(String expression) { StackInterface
while(isBalanced && (index < characterCount)) { nextCharacter = expression.charAt(index); switch (nextCharacter) { case '(': case '[': case '{': openDelimiterStack.push(nextCharacter); break; case ')': case ']': case '}': if(openDelimiterStack.isEmpty()) { isBalanced = false; } else { char openDelimiter = openDelimiterStack.pop(); isBalanced = isPaired(openDelimiter, nextCharacter); } break; default: break; } index ++; } if(!openDelimiterStack.isEmpty()) { isBalanced = false; } return isBalanced; }
private static boolean isPaired(char open, char close) { return (open == '(' && close == ')') || (open == '[' && close == ']') || (open == '{' && close == '}'); } }
StackInterface.java
import java.util.EmptyStackException;
public interface StackInterface
/** Removes and returns this stack's top entry * @return The object at the top of the stack * @throws EmptyStackException if the stack is empty*/ T pop();
/** Retrieves this stack's top entry. * @return The object at the top of the stack. * @throws EmptyStackException if the stack is empty.*/ T peek();
/** Detects whether this stack is empty * @return True if the stack is empty. */ boolean isEmpty();
/** removes all entries from this stack */ void clear(); }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
