Advertisement
brilliant_moves

StackNames.java

Dec 2nd, 2013
412
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.29 KB | None | 0 0
  1. import java.util.Scanner;   // for user input
  2.  
  3. public class StackNames {
  4.  
  5.     public static void main (String[] args) {
  6.         final int n = 10;
  7.         Stack stack = new Stack(n); // size of stack is 10 in this case
  8.         Scanner scan = new Scanner(System.in);
  9.  
  10.         for (int i=0; i<n; i++) {
  11.             System.out.print("Enter name ["+(i+1)+"]: ");
  12.             String s = scan.nextLine();
  13.             stack.push(s);
  14.         }
  15.  
  16.         while (!stack.isEmpty()) {
  17.             System.out.println( stack.pop()); // print 10 names removed
  18.         }
  19.     } // end main()
  20. } // end class StackNames
  21.  
  22. class Stack {
  23.     private static final int DEFAULT_SIZE = 10;
  24.     private static int size;
  25.     private static int top;
  26.     private static String[] values;
  27.  
  28.     public Stack() {
  29.         this (DEFAULT_SIZE);
  30.     }
  31.  
  32.     public Stack(int size) {
  33.         this.size = size;
  34.         values = new String[size];
  35.         top = -1;
  36.     }
  37.  
  38.     public static boolean isFull() {
  39.         if (top < size - 1) {
  40.             return false;
  41.         } else {
  42.             return true;
  43.         }
  44.     }
  45.  
  46.     public static boolean isEmpty() {
  47.         if (top == - 1) {
  48.             return true;
  49.         } else {
  50.             return false;
  51.         }
  52.     }
  53.  
  54.     public static void push(String x) {
  55.         if (!isFull()) {
  56.             top++;
  57.             values[top] = x;
  58.         }
  59.     }
  60.  
  61.     public static String pop() {
  62.         String netVal = "";
  63.         if (!isEmpty()) {
  64.             netVal = values[top];
  65.             top--;
  66.         }
  67.         return netVal;
  68.     }
  69. } // end class Stack
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement