//封装一个类型的栈
public class aaa2
{
private int maxsize;
private double element[];
private int top;
public aaa2(int n)
{
maxsize=n;
top=0;
element =new double[n];
}
public double gettop()
{
if(isempty())
{ System.out.println("there is no element.");
return 0.0;
}
else
{ return element[top--];//注意return 一定放在最后
}
}
public void push(double a)
{
if(isfull())
System.out.println("there is full of element");
else
{ top++;
element[top]=a;
}
}
public boolean isfull()
{
return (top==maxsize);
}
public boolean isempty()
{
return (top==0);
}
}
public class aaaa2
{
public static void main(String args[])
{
aaa2 stack=new aaa2(3);
double a,b,c,d,m;
a=1.0;
b=20.2;
c=21.3;
d=25.6;
stack.push(a);
stack.push(b);
stack.push(c);
m=stack.gettop();
System.out.println("m="+m);
}
}
以上是我写地小程序,就是一个栈,然后进栈出栈,可是再编译时没问题,但运行时发现了越界地错误。ArrayIndexOutOfBoundsException,当我去掉 c=21.3; d=25.6;就没有这样的错误了。可是我明明在发生越界时会打印出
("there is full of element");,
怎么会发生这样地情况呢?谢谢大家。请看一下。由于条件有限,没法每天上网看,所以可能无法及时回复大家。