Stack Code Example Java Programming



package yasolution.org;

import java.util.Scanner;

public class YaSolution {

static int top=-1;

static int[] stack= new int[5];

static int input;

static boolean isRunning=true; 

public static void main(String[] arg){  

 do{

  System.out.println();

  System.out.println("===========Menu===========");

  System.out.println("1. Add");

  System.out.println("2. Remove");

  System.out.println("3. Show");

  System.out.println("4. Exit");

  System.out.print("Select option: ");

  Scanner scan = new Scanner(System.in);

  input = scan.nextInt();

  switch(input){

  case 1:

   push();

   break;

  case 2:

   pop();

   break;

  case 3:

   show();

   break;

  case 4:

   isRunning=false;

   break;

  default:

   System.out.println("Invalid option.");

  }

 }while(isRunning);

}

static void push(){

 if(top==4)

  System.out.println("Stack is full.");

 else{

  top++;

  System.out.print("Input value: ");

  Scanner scan = new Scanner(System.in);

  stack[top]=scan.nextInt();

 }

}

static void pop(){

 if(top==-1)

  System.out.println("Stack is empty.");

 else{

  System.out.println("Stack removed. Success!.");

  top--;

 }

}



static void show(){

 if(top==-1)

  System.out.println("Stack is empty.");

 else{

  System.out.println("\nStack size is "+(top+1));

  System.out.print("Stack data : ");

  for(int i=0;i<=top;i++)

   System.out.print(stack[i]+"     ");

  System.out.println();

 }

}

}