Skip to content

Instantly share code, notes, and snippets.

@mcrumm
Created April 29, 2014 01:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcrumm/11388987 to your computer and use it in GitHub Desktop.
Save mcrumm/11388987 to your computer and use it in GitHub Desktop.
//TestStack.java
//Michael Crumm 2010-10-04
import java.io.*;
import java.util.Scanner;
import stack.*;
public class TestStack
{
//Prompts the user for Integers and pushes them onto the stack.
//The Stack's size and String representation are printed.
//The Stack's pop method is called in a loop to display input
//in reverse order.
public static void main(String[] args) throws IOException
{
Stack theStack = new ArrayStack(5);
readIntegersIntoStack(theStack);
System.out.println("There are " + theStack.size() + " elements in the stack.");
System.out.println("The stack: " + theStack.toString());
System.out.println("Your data reversed:");
removeIntegersFromStack(theStack);
}
//Reads a list of Integers from Standard Input and pushes them onto theStack
public static void readIntegersIntoStack(Stack theStack) throws IOException
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a list of integers, one per line."
+ "\n Press enter to stop.");
String line = null;
while(true) {
line = scanner.nextLine();
if(line.equals("")) {
break;
}
theStack.push(new Integer(line));
}
}
//Pops each element from theStack and prints it to Standard Output until
//the stack is empty.
public static void removeIntegersFromStack(Stack theStack)
{
while(!theStack.isEmpty()) {
System.out.println(theStack.peek().toString());
theStack.pop();
}
System.out.println("Stack is now empty.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment