I'm starting out to work on DS in Java for the first time and thought that some inputs will get me going to more data structures. I implemented a stack which is non-generic. I followed some of the posts and realized that the top pointer should not be at -1. I know this is a very basic implementation (probably the worst). The LIFO part is working well. I am looking for suggestions on what are some ways to improve this code other than making this to be Generic Stack.
Code:
import java.util.*;
//******************************* Stack Demo Class **********//
class StackDemo{
int stackarray[] , top;
// Constructor
StackDemo(int size){
stackarray = new int[size+1];
top = 0;
System.out.println("The size of stack array is "+ (stackarray.length-1));
}
// *********************PUSH******************************//
void push(int ele){
if(top == stackarray.length - 1){
System.out.println("Stack Overflow");
}
else{
top++;
stackarray[top] = ele;
}
} // Push Method
// *********************POP******************************//
int pop(){
int lastElement = 0;
if(top == 0){
System.out.println("Stack is Underflow");
}
else{
lastElement = stackarray[top];
top--;
}
return lastElement;
} // Pop Method
// *********************DISPLAY******************************//
void display(){
if(top == 0){
System.out.println("Nothing to Display");
}
for (int i = 1; i<=top ; i++){
System.out.print(stackarray[i] +"\t");
}
System.out.println("");
} // Display Method
}
// *****************************Main Class*******************//
public class Stacks{
public static void main(String args[]){
StackDemo sd = new StackDemo(10);
Scanner s = new Scanner(System.in);
while(true){
System.out.println("Enter your choice : \n 1.Push \n 2.Pop \n 3.Display \n 4.Exit");
int choice = s.nextInt();
switch(choice){
case 1:
System.out.println("Enter an Element to push");
int pushElement = s.nextInt();
sd.push(pushElement);
break;
case 2:
int popElement = sd.pop();
System.out.println("Popped Element is "+popElement);
break;
case 3:
sd.display();
break;
case 4:
System.exit(0);
break;
default:
System.out.println("Enter valid choice");
} // Switch Closing
} // While Closing
} // Main method
} // Main class