fork(1) download
  1.  
  2. class Practicestack {
  3.  
  4. public static void main(String[] args) {
  5. Stackx newStack = new Stackx(5);
  6. newStack.push("redShirt");
  7. newStack.push("greenShirt");
  8. newStack.push("yellowPants");
  9. newStack.push("purpleSocks");
  10. newStack.push("pinkSocks");
  11. newStack.peek();
  12.  
  13. //Display the Full Stack
  14. newStack.display();
  15. //Test removing a value using pop method
  16. newStack.pop();
  17.  
  18. newStack.display();
  19. }
  20. }
  21. class Stackx {
  22. private int maxSize; //number of items in stack
  23. private String[] stackArray;
  24. private int top; // top of stack
  25.  
  26. public Stackx(int arraySize) {
  27. maxSize = arraySize;
  28. stackArray = new String[maxSize];
  29. top = -1;
  30. }
  31.  
  32. public void push(String a) { //put value on top of stack
  33. if (top == maxSize - 1)
  34. {
  35. System.out.println("Stack is full");
  36. } else {
  37.  
  38. top = top + 1;
  39. stackArray[top] = a;
  40. }
  41. }
  42.  
  43. public String pop() { //take item from top of stack
  44. if (!isEmpty())
  45. return stackArray[top--]; // access item, decrement top
  46. else {
  47. System.out.println("Stack is Empty");
  48. throw null;
  49. }
  50. }
  51.  
  52. public String peek() //peek at the top of the stack
  53. {
  54. return stackArray[top];
  55. }
  56.  
  57. public boolean isEmpty() { //true if stack is empty
  58. return top == -1;
  59. }
  60.  
  61. public void display() {
  62.  
  63. for (int i = 0; i <= top; i++) {
  64. System.out.print(stackArray[i] + " ");
  65. }
  66. System.out.println();
  67. }
  68. } // End class stackx
Success #stdin #stdout 0.05s 4386816KB
stdin
Standard input is empty
stdout
redShirt greenShirt yellowPants purpleSocks pinkSocks 
redShirt greenShirt yellowPants purpleSocks