Sunday 30 March 2014

JAVA PROGRAMS-Stack Program In Java

Stack Program In Java

Program Name:- stackdemo.java

import java.io.*;
class stack
{
int s[]=new int[100];
int top;
void stack()
 {
 top=0;
 System.out.println("\n The stack is empty");
 }
public void push()throws IOException
 {
 DataInputStream inp=new DataInputStream(System.in);
 int x;
 if(top==100)
  {
  System.out.println("The Stack is full");
  }
 else
  {
  System.out.print("\n Enter the value  :");
  x=Integer.parseInt(inp.readLine());
  s[top]=x;
  top++;
  System.out.println("\n The value is pushed");
  }
 }
public void pop()throws IOException
 {
 DataInputStream inp=new DataInputStream(System.in);
 int y;
 if(top==0)
  {
  System.out.println("\n The stack is empty");
  }
 else
  {
  top--;
  y=s[top];
  s[top]='\0';
  System.out.println("\n The value is poped");
  }
 }
void display()
 {
 int i;
 if(top==0)
 {
  System.out.println("\nThe stack is empty");
  }
 else
  {
   System.out.println("\nValues are top-->");
  }
 for(i=top-1;i>=0;i--)
  System.out.println(s[i]);
 }
}
public class stackdemo
{
public static void main(String args[])throws IOException
 {
 stack in=new stack();
 int item=0;
 int opt=1;
 String s=new String();
 while(opt<4)
 {
 System.out.println("\n\n\t\t Main menu\n\n1.push\n\n2.Pop\n\n3.Display\n\n4.Exit\n\nSelection the option");
 DataInputStream din=new DataInputStream(System.in);
 s=din.readLine();
 opt=Integer.parseInt(s);
 switch(opt)
  {
   case 1:
   System.out.println("\nEnter the elementis add");
   in.push();
   break;
   case 2:
   System.out.println("\nEnter the delete item");
   in.pop();
   break;
   case 3:
   System.out.println("\nThe stack element is:");
   in.display();
   break;
   default:
   opt=4;
   }
  }
 }
}

No comments:

Post a Comment