Here I am implementing Stack Array in java with StackADT, I have created 3 files
1. StackADT.java 2. AStack.java 3. AStack_Test.java
// StackADT.java
public interface StackADT
{
public int size();
public boolean isEmpty();
public Object top();
public void push(Object element);
public Object pop();
}
// 2. AStack.java
public class AStack implements StackADT
{
Object Array[];
int top=-1;
AStack(int size)
{
Array=new Object[size];
}
public int size()
{
return top;
}
public boolean isEmpty()
{
if (top<0)
{
return true;
}
else
return false;
}
public Object top()
{
return Array[top];
}
public void push(Object element)
{
try
{
Array[++top]=element;
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
public Object pop()
{
try
{
Object result=Array[top];
top=top-1;
return result;
}
catch (ArrayIndexOutOfBoundsException e)
{
return e.getMessage();
}
}
public void exit()
{
System.exit(0);
}
}
// 3. AStack_Test.java
import java.util.Scanner;
class AStack_Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int choice,size,el;
System.out.println("Please enter size of the Array stack");
size=sc.nextInt();
AStack AS=new AStack(size);
while (true)
{
System.out.println("Please enter you choice");
System.out.println(" 1 for insert or push \n 2 for is Stack empty \n 3 to get top element \n 4 to pop the lement");
System.out.println(" 5 to exit");
choice=sc.nextInt();
switch (choice)
{
case 1:
System.out.println("Please enter Enter your element");
el=sc.nextInt();
AS.push(el);
break;
case 2:
System.out.println(AS.isEmpty());
break;
case 3:
if(!AS.isEmpty())
{
System.out.println("top element is ");
System.out.println(AS.top());
}
else
System.out.println("\nArray stack is empty\n");
break;
case 4:
System.out.println("\nPoped element is\n ");
System.out.println(AS.pop());
break;
case 5:
AS.exit();
default:
System.out.println("Please choose correct choice");
}
}
}
}
No comments:
Post a Comment