标题:[求助]出现越界错误
取消只看楼主
autumnleaf
Rank: 1
等 级:新手上路
帖 子:17
专家分:0
注 册:2006-10-22
 问题点数:0 回复次数:5 
[求助]出现越界错误

//封装一个类型的栈
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");,

怎么会发生这样地情况呢?谢谢大家。请看一下。由于条件有限,没法每天上网看,所以可能无法及时回复大家。

搜索更多相关主题的帖子: element 越界 public double return 
2006-11-28 00:36
autumnleaf
Rank: 1
等 级:新手上路
帖 子:17
专家分:0
注 册:2006-10-22
得分:0 

谢谢大家,我知道了,运行下来时对地,我觉得还有一种改法,//封装一个类型的栈
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);

}

这样运行下来也对地,谢谢啊


2006-11-28 12:30
autumnleaf
Rank: 1
等 级:新手上路
帖 子:17
专家分:0
注 册:2006-10-22
得分:0 
哪有白给我????我终于找出问题了呀,都不知道有多开心。。。。。,你们不给我,我这辈子都不知道错在哪里

2006-11-28 16:48
autumnleaf
Rank: 1
等 级:新手上路
帖 子:17
专家分:0
注 册:2006-10-22
得分:0 
我知道了呀,只是想到另一个方法,也可以解决问题啊
,真冤啊,

2006-11-28 16:51
autumnleaf
Rank: 1
等 级:新手上路
帖 子:17
专家分:0
注 册:2006-10-22
得分:0 
总之谢谢拉,各位!!!!!!!!!!!!

2006-11-28 16:52
autumnleaf
Rank: 1
等 级:新手上路
帖 子:17
专家分:0
注 册:2006-10-22
得分:0 

2006-11-28 16:53



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-105797-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.024520 second(s), 8 queries.
Copyright©2004-2025, BCCN.NET, All Rights Reserved