//封装一个类型的栈
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");,
怎么会发生这样地情况呢?谢谢大家。请看一下。由于条件有限,没法每天上网看,所以可能无法及时回复大家。
----------------解决方案--------------------------------------------------------
你要处理这个错误 话要写异常处理的吧!!
----------------解决方案--------------------------------------------------------
top++;
element[top]=a;
问题就出现在这里
你是先自加后赋值的
所以,你element[0]是不会放东西进去的
当你放到第三个的时候,检查的时候还没有满,所以加进去时候就越界了
----------------解决方案--------------------------------------------------------
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);
}
----------------解决方案--------------------------------------------------------
楼上的 写到一起不就好了嘛....element[top++]=a
----------------解决方案--------------------------------------------------------
谢谢大家,我知道了,运行下来时对地,我觉得还有一种改法,//封装一个类型的栈
public class aaa2
{
private int maxsize;
private double element[];
private int top;
public aaa2(int n)
{
maxsize=n;
top=0;
element =new double[n];//改为 element =new double[n+1];
}
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);
}
这样运行下来也对地,谢谢啊
----------------解决方案--------------------------------------------------------
你这又是何必呢,
这样改的话,第一个元素永远是空在那里的
----------------解决方案--------------------------------------------------------
看来上面的帖子都白给他写了。。。
----------------解决方案--------------------------------------------------------
----------------解决方案--------------------------------------------------------
看来上面的帖子都白给他写了。。。
确实是白给他写了
----------------解决方案--------------------------------------------------------