StackTest.java 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /**
  2. * Driver program to allow command line user to interface with a MyStack instance.
  3. *
  4. * Project 1
  5. *
  6. * @author Thomas Flucke tflucke
  7. * @author Lara Luu ljluu
  8. *
  9. * @since 2015/10/07
  10. *
  11. * @see MyStack
  12. */
  13. import java.util.EmptyStackException;
  14. import java.util.Scanner;
  15. public class StackTest
  16. {
  17. /**
  18. * Runs the program.
  19. */
  20. public static void main(String... args)
  21. {
  22. Scanner in = new Scanner(System.in); // class to read from console
  23. MyStack<String> stack = new MyStack<String>(); // initializes stack to manipulate inputs onto
  24. System.out.println("Choose one of the following operations:");
  25. System.out.println("- push/add (enter the letter a)");
  26. System.out.println("- pop/delete (enter the letter d)");
  27. System.out.println("- peek (enter the letter p)");
  28. System.out.println("- check if the list is empty (enter the letter e)");
  29. System.out.println("- Quit (enter the letter q)");
  30. String line; // variable to store the read input by line
  31. System.out.println("Please insert a menu choice.");
  32. while (!(line = in.nextLine()).equals("q"))
  33. {
  34. if (line.length() != 1)
  35. {
  36. System.out.println("Invalid choice");
  37. }
  38. char option = line.charAt(0);; // stores option to be read in switch statement
  39. try
  40. {
  41. switch (option)
  42. {
  43. case 'a':
  44. String pushed = in.nextLine(); // saves next input to be pushed onto the stack
  45. stack.push(pushed);
  46. System.out.println(pushed+" pushed in");
  47. break;
  48. case 'd':
  49. System.out.println(stack.pop()+" popped out");
  50. break;
  51. case 'p':
  52. System.out.println(stack.peek()+" on the top");
  53. break;
  54. case 'e':
  55. System.out.println(stack.isEmpty()? "empty":"not empty");
  56. break;
  57. default:
  58. System.out.println("Invalid choice");
  59. }
  60. }
  61. catch (EmptyStackException ese)
  62. {
  63. System.out.println("Invalid operation on an empty stack");
  64. }
  65. System.out.println("Please insert a menu choice.");
  66. }
  67. System.out.println("quitting");
  68. in.close();
  69. }
  70. }