// data member
private int size ;
private int top ;
private Object[] stack ;
// Create Stack [ Constauctor ]
public Stack_data(int size) {
this.size = size ;
this.top = -1 ; // 0 - (1) Start Stack Top
stack = new Object[size] ;
}
// input data to stact Object Array
public void inputStack(Object data){
// Check top < size[size -1] of Stack
if( top + 1 < size ){
top++ ;
stack[top] = data ;
}else{
JOptionPane.showMessageDialog(null,"The Stack is FULL.");
}
}
// Removed Stack Of memory
public Object getStack() throws Exception{
// check Stack data != NULL
if( top > -1 ){
Object data = stack[top] ;
top--;
return data ;
}else{
throw new Exception("Stuck is NULL");
}
}
public int getTop() {
return this.top;
}
public void showStack() {
System.out.println("======== Data in Stact ========");
for(int i = 0 ; i <= this.top ; i++){
System.out.print(stack[i]+"\t");
}
System.out.println("\n"+"position top="+this.top);
System.out.println("----------------------------------------------------");
}
public static void main(String args[]){
int size = 0 ;
// How to Create Stack ?
while(true){
try{
size = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter a number for Create Stack size : "));
break;
}catch(NumberFormatException number){
JOptionPane.showMessageDialog(null,"Error..." + number.getMessage() + "\nPlease enter numbers again.");
break;
}
}//while
// Create Stact
Stack_data newStack = new Stack_data(size);
System.out.println("stack size = "+newStack.stack.length);
// Input data for Stact
for(int i = 0 ; i < newStack.size ; i++){
try{
String item = JOptionPane.showInputDialog(null,"Enter of Stact data is " + (i+1) + " : ");
newStack.inputStack(Integer.parseInt(item));
System.out.println("Push : "+item);
}catch(Exception e) {
JOptionPane.showMessageDialog(null,"Error..., " + e.getMessage());
break;
} //try
}//for
// show data in Stack
newStack.showStack();
// Remove data from Stack
try{
System.out.println("pop : "+newStack.getStack());
newStack.showStack();
}catch(Exception e){
JOptionPane.showMessageDialog(null,"Error..., " + e.getMessage());
}