package OOPSnStacks;
public class DynamicStackClient {
public static void main(String[] args) throws Exception {
Stackusingarray stack = new DynamicStack(5);
for(int i = 1; i<=5; i++)
{
stack.push(i * 10);
stack.display();
}
stack.push(60);
stack.push(70);
stack.push(80);
stack.display();
System.out.println(stack.top());
while(!stack.isEmpty())
{
stack.display();
stack.pop();
}
//System.out.println(stack.top());
//stack.pop();
}
}
dynamic stack -
package OOPSnStacks;
public class DynamicStack extends Stackusingarray {
public DynamicStack() throws Exception
{
this(DEFAULT_CAPACITY);
}
public DynamicStack(int capacity) throws Exception
{
super(capacity);
}
public void push(int item) throws Exception
{
if(this.size() == this.data.length)
{
int [] arr = new int[2*this.data.length];
for(int i=0; i<this.size(); i++)
{
arr[i] = this.data[i];
}
this.data = arr;
super.push(item);
}
}
}
stackusingarray -
package OOPSnStacks;
public class Stackusingarray {
//private int [] data;
//private int top;
//for dynamic stack we are creating data and top as protected
protected int [] data;
protected int top;
public static final int DEFAULT_CAPACITY = 10;
public Stackusingarray() throws Exception
{
this(DEFAULT_CAPACITY);
}
public Stackusingarray(int capacity) throws Exception
{
//exception
if(capacity<1)
{
throw new Exception("INVALID CAPACITY");
}
this.data= new int[capacity];
this.top = -1;
}
public int size()
{
return this.top+1;
}
public boolean isEmpty()
{
return this.size() == 0;
}
public void push(int value) throws Exception
{
if(this.size() == this.data.length)
{
throw new Exception("STACK IS FULL");
}
this.top++;
this.data[this.top] = value;
}
public int pop() throws Exception
{
if(this.size() == 0)
{
throw new Exception("STACK IS EMPTY");
}
int rv = this.data[this.top];
this.data[this.top] = 0;
this.top--;
return rv;
}
public int top() throws Exception
{
if(this.size() == 0)
{
throw new Exception("STACK IS empty");
}
int rv = this.data[this.top];
return rv;
}
public void display()
{
for(int i = this.top; i>=0;i--)
{
System.out.print(this.data[i]+", ");
}
System.out.println("END");
}
}
error is coming given below as
Exception in thread “main” java.lang.Exception: STACK IS empty
at OOPSnStacks.Stackusingarray.top(Stackusingarray.java:60)
at OOPSnStacks.DynamicStackClient.main(DynamicStackClient.java:19)
END
END
END
END
END
END