【问题标题】:ArrayList Throws Error When Error Says Length is Longer当错误表示长度较长时,ArrayList 引发错误
【发布时间】:2013-10-28 01:41:30
【问题描述】:

对于一些背景信息,我正在制作一个商店系统,而收集的硬币存储在一个数组中,然后在购买物品时移除。

问题是,即使硬币数量大于价格(即 80 个硬币,但仅从 ArrayList 中减去 75),也会引发此错误。

java.lang.ArrayIndexOfBoundsException: length=202; index=-1;

代码循环让我很难过(我还有几个这样的,问题似乎总是只剩下几个硬币):

if(this.name.equals("SHOTGUN BURST") && gamescreen.map.getCoinSize() >= this.price) {
player.isShotty = true;
for(int f = 0; f < this.price; f++) { 
       gamescreen.map.coinsCollect.remove(gamescreen.map.getCoinSize() - 1 - f);
   }
}

【问题讨论】:

  • gamescreen.map.getCoinSize() - 1 - f 计算结果为 -1。您不能有负索引。
  • 如果 f = 0? -1 是因为数组从 0 开始,所以最大数不是数组的实际大小。而 f 是指向我要删除的索引(从最后一个开始)。
  • 您确定您的 getCoinSize() 正在返回正确的值吗?比如有币收(0, 1, 2, 3),大小必须是4。

标签: java android arraylist indexoutofboundsexception


【解决方案1】:

-1 的数组索引(堆栈跟踪表明您正在尝试访问)总是超出范围。

出于调试目的,暂时将您的代码更改为:

for(int f = 0; f < this.price; f++) {
   System.out.println("f = %d", f);
   System.out.println("getCoinSize() = %d", gamescreen.map.getCoinSize());
   System.out.println("Array Index = %d", (gamescreen.map.getCoinSize()-1-f); 
   gamescreen.map.coinsCollect.remove(gamescreen.map.getCoinSize()-1-f);
}

不要说“出于某种原因 X 正在发生”。使用某种调试方法。输出语句的替代方法是使用断点并逐行单步执行程序。

【讨论】:

  • 这是他的问题的答案吗?
  • 无论出于何种原因,从我的原始硬币大小中减去 1 都会给我一个以二为单位倒数的输出(即,我有 155 个硬币,154 - 1, 154 - 2...不知何故给了我 153 , 151, 149...)。
  • 我明白了。由于我还不能回答我自己的问题,我会说它基本上归结为存储我拥有的初始硬币数量,所以 for 循环没有考虑到我在搜索索引时已经删除的那些。但基本上,“-1 的数组索引总是越界”!
  • int j = gamescreen.map.coinsCollect.size(); for(int f = 0; f
  • 如果f==0,那么(j-1)(j-f-1)不一样吗?
猜你喜欢
  • 2016-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-11
  • 2021-04-09
  • 2020-07-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多