You are on page 1of 2

// Simulate a very simple stack of integers

import java.util.*;
public class ABStack
{
public static void main (String [ ] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter maximum stack capacity: ");
int cap = input.nextInt();
int [ ] myStack = new int[cap]; // create the stack
int top = 0; // index of next available position and/or size of
current stack
System.out.println("Enter a to add with a value to add, or p to
pop, ");
System.out.print("or 'EXIT' to quit): ");
String command = input.next();
while (command.equals("EXIT") == false) // as long as EXIT was n
ot entered
{
if (command.equals("a")) // add first
{
int value = input.nextInt(); // get value follow
ing command
if (top < myStack.length) // we still have room.
..
{
myStack[top] = value;
top = top + 1;
}
else
{
System.out.println("The stack is full!")
;
}
}
else if (command.equals("p")) // remove an item
{
if (top > 0) // we have at least 1 element left
{
top = top - 1; // move down one space
myStack[top+1] = -99999; // clear with a
fixed value
input.nextLine();
}
else
{
System.out.println("The stack is empty!"
);
}
}
else

{
System.out.println("Invalid command!");
}
System.out.println("Current stack contents:");
printStack(myStack, top);
// Check to see if we should repeat
System.out.println("Enter a to add with a value to add,
or p to pop, ");
System.out.print("or 'EXIT' to quit): ");
command = input.next();
}
}
static void printStack (int [] stack, int max)
{
for (int i = 0; i < max; i++)
{
System.out.print(stack[i] + " ");
}
System.out.println();
}
}

You might also like