Advertisement
Md_Sakib_Hossain

Stack Push(), Pop()

Mar 11th, 2021 (edited)
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.04 KB | None | 0 0
  1. import java.util.*;
  2. import java.lang.*;
  3. public class AllDataStructure{
  4.  
  5.     public static Scanner scan = new Scanner(System.in);
  6.     public static int array[] = new int[5];
  7.     public static int choice;
  8.     public static int elementToPush;
  9.     public static int countIndex=-1;
  10.     public static String takeAnswer;
  11.  
  12.     public static void push(int item){
  13.         try
  14.         {
  15.                array[countIndex] = item;
  16.                 printArray();
  17.         }catch(ArrayIndexOutOfBoundsException e){
  18.          System.out.println("Stack Overflow");
  19.         }
  20.     }
  21.  
  22.     public static void pop(){
  23.         if(countIndex==-1){
  24.             System.out.println("Stack Underflow");
  25.         }else{         
  26.         countIndex=countIndex-1;
  27.         printArray();
  28.         }
  29.     }
  30.  
  31.     public static void printArray(){
  32.         for (int i=0;i<countIndex+1;i++) {
  33.             System.out.print(array[i]+" ");
  34.         }
  35.         System.out.println("");
  36.     }
  37.  
  38.     public static void chooseOperation(){
  39.  
  40.         switch (choice)
  41.         {
  42.  
  43.             case 1: System.out.print("Enter element to be pushed: ");
  44.                     countIndex=countIndex+1;
  45.                     elementToPush = scan.nextInt();
  46.                     push(elementToPush);
  47.                     break;
  48.  
  49.             case 2: pop();
  50.                     break;
  51.         }
  52.  
  53.     }
  54.  
  55.  
  56.     public static void main(String[] args) {
  57.  
  58.          System.out.print("Which operation do you want to do?\n1. Push \n2. Pop\n");
  59.          choice=scan.nextInt();
  60.          chooseOperation();
  61.          System.out.print("Which operation do you want to do?\n1. Push \n2. Pop\n");
  62.          choice=scan.nextInt();
  63.          chooseOperation();
  64.          System.out.print("Which operation do you want to do?\n1. Push \n2. Pop\n");
  65.          choice=scan.nextInt();
  66.          chooseOperation();
  67.          System.out.print("Which operation do you want to do?\n1. Push \n2. Pop\n");
  68.          choice=scan.nextInt();
  69.          chooseOperation();
  70.          System.out.print("Which operation do you want to do?\n1. Push \n2. Pop\n");
  71.          choice=scan.nextInt();
  72.          chooseOperation();
  73.          System.out.print("Which operation do you want to do?\n1. Push \n2. Pop\n");
  74.          choice=scan.nextInt();
  75.          chooseOperation();
  76.          
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement