Unable to implement stack through this code...
UseStack.java
class UseStack{
public static void main(String[] args) {
Scanner obj = new Scanner(System.in);
System.out.println("Enter the size of Stack....");
int n = obj.nextInt();
Push push = new Push(n);
Pop pop = new Pop(n);
while(true){
System.out.println("1: Push");
System.out.println("2: pop");
System.out.println("3: Show");
int choice = obj.nextInt();;
switch(choice){
case 1:
push.push();
break;
case 2:
pop.pop();
break;
case 3:
push.show();
break;
default:
System.out.println("Invalid Option");
break;
}
}
}
}
Stack.java
class Stack {
public int arr[];
public int top;
public int capacity;
Stack(int size){
this.arr = new int[size];
this.capacity = size;
this.top = -1;
}
}
Push.java
class Push extends Stack {
Push(int size) {
super(size);
}
private static Scanner obj;
public void push(){
obj = new Scanner(System.in);
System.out.println("Enter Value to push...");
int value = obj.nextInt();
System.out.println("Value : "+value);
if(top==capacity-1){
System.out.println("StackOverflow");
return;
}
else{
top++;
System.out.println("Top : "+top);
arr[top]=value;
System.out.println("Pushed... "+arr[top]);
}
}
public void show(){
if(top==-1){
System.out.println("StackUnderFlow");
return;
}
else{
System.out.println("Stack Elements : ");
for(int i=top;i>=0;i--){
System.out.println(arr[i]+" ");
}
}
}
}
Pop.java
public class Pop extends Stack {
Pop(int size) {
super(size);
}
public void pop(){
if(top==-1){
System.out.println("StackUnderflow-pop");
return;
}
else{
System.out.println("Top : "+top);
System.out.println("Poped.. "+arr[top]);
top--;
}
}
}
Problem
In this implementation pop() is not working.....
I think for this Pop class needs to extends both Stack and Push classes as so this is not possible in java ,If I'm wrong can anyone help me with this how to resolved it...
See Question&Answers more detail:os