I am unable to understand why my value is not storing in the stack..
UseStack.java
package test;
import java.util.Scanner;
class UseStack{
private static Scanner obj;
public static void main(String[] args) {
obj = new Scanner(System.in);
System.out.println("Enter the size of Stack....");
int n = obj.nextInt();
Stack stack = new Stack(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 = new Push(n);
push.push();
break;
case 2:
Pop pop = new Pop(n);
pop.pop();
break;
case 3:
Push push1 = new Push(n);
push1.show();
break;
default:
System.out.println("Invalid Option");
break;
}
}
}
}
Stack.java
package test;
class Stack {
public int arr[];
public int top;
public int capacity;
public Stack(int size){
this.arr = new int[size];
capacity = size;
top = -1;
}
}
Push.java
package test;
import java.util.Scanner;
class Push extends Stack {
public 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();
if(top==capacity-1){
System.out.println("StackOverflow");
return;
}
else{
top++;
arr[top]=value;
System.out.println("Pushed...");
}
}
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
package test;
class Pop extends Push{
public Pop(int size) {
super(size);
}
public void pop(){
if(top==-1){
System.out.println("StackUnderflow");
return;
}
else{
System.out.println("Poped.. "+arr[top]);
top--;
}
}
}
Please execuse my ignorance for posting the whole code and there were several questions has been already asked on this topic but what should i have to do to overcome with this error...
Error
As i pushed two values in array and then tried to show the element , stackunderflow i got....