I am doing this exercise my professor told the class to do. "Write a method public static void removeDownTo (StackX stack, long ob): It pops all values off the stack down to but not including the first element it sees that is equal to the second parameter. If none are equal, leave the stack empty."
This is my code.
StackX
class:
public class StackX {
private static int maxSize; // size of stack array
private static long[] stackArray;
private int top; // top of stack
//--------------------------------------------------------------
public StackX(int s) // constructor
{
maxSize = s; // set array size
stackArray = new long[maxSize]; // create array
top = -1; // no items yet
}
//--------------------------------------------------------------
public void push(long j) // put item on top of stack
{
stackArray[++top] = j; // increment top, insert item
/** if (isFull() ) {
System.out.println("Push error: Stack is full. Push failed.");
} else {
stackArray[++top] = j;
} */
}
//--------------------------------------------------------------
public long pop() // take item from top of stack
{
return stackArray[top--]; // access item, decrement top
/** if(!isEmpty()) {
return stackArray[top--];
} else {
System.out.println("Error: Stack is empty. Returning -1");
return -1;
}
*/
}
//--------------------------------------------------------------
public long peek() // peek at top of stack
{
return stackArray[top];
}
//--------------------------------------------------------------
public boolean isEmpty() // true if stack is empty
{
return (top == -1);
}
//--------------------------------------------------------------
public boolean isFull() // true if stack is full
{
return (top == maxSize - 1);
}
}
StackApp
class:
public class StackApp
{
public static void removeDownTo(StackX stack, long n) {
long x;
while(!stack.isEmpty()) {
x = stack.peek();
stack.pop();
if(stack.isEmpty()) {
if(x==n) {
stack.push(x);
}
}
}
}
public static void main(String[] args)
{
StackX theStack = new StackX(10); // make new stack
theStack.push(20); // push items onto stack
theStack.push(40);
theStack.push(60);
theStack.push(80);
// theStack.push(16);
// theStack.push(10);
while( !theStack.isEmpty() ) // until it's empty,
{ // delete item from stack
long value = theStack.pop();
System.out.print(value); // display it
System.out.print(" ");
} // end while
System.out.println("");
removeDownTo(theStack, 60);
System.out.print("");
} // end main()
} // end class StackApp ##
This is the output it shows: 80, 60, 40, 20.
However, I think the output this exercise is asking for is to get 60, 40, 20. What am I doing wrong?