【问题标题】:ArrayIndexOutOfBoundsException in processing处理中的 ArrayIndexOutOfBoundsException
【发布时间】:2014-06-16 07:13:27
【问题描述】:

所以我一直在研究一个小型坦克程序,但每当我尝试运行它时,我都会在第 477 行 (http://pastebin.com/k4WNXE6Q) 收到 ArrayIndexOutOf BoundsException。

void placeStations(int Number) {
  for (int i = 0; i<Number; i++) {
    stations.add(new RefillStation(int(random(0, width)), int(random(0, height))));

    // This line of code refuses to work. I get an 'ArrayIndexOutOfBoundsException: -3'
    RefillStation station = stations.get(i);

    for (Tank tank : tanks) {
      if (station.getRectangle().intersects(tank.getRectangle())) {
        station.kill();
        i=i-1;
      }
    }
    for (Obstacle obstacle : obstacles) {
      if (station.getRectangle().intersects(obstacle.getRectangle())) {
        station.kill();
        i=i-1;
      }
    }
  }
}

我已经尝试了几个小时来查找错误,但我看不出与上面的方法没有什么不同,这似乎工作正常。我在某些地方使用 'i' 类型的循环,因为每当我尝试从现代 for 循环中的索引中删除某些内容时,它都会给我一个大小更改异常。关于我可以做些什么来解决这个问题的任何想法?

【问题讨论】:

    标签: java arrays processing indexoutofboundsexception


    【解决方案1】:

    与 Tanks 和 Obstacles 的多次重叠会导致 i 反复减少。但你只想杀掉电台一次:跳出循环。

     for (Tank tank : tanks) {
       if (station.getRectangle().intersects(tank.getRectangle())) {
         station.kill();
         i=i-1;
         break;
       }
     }
    

    【讨论】:

      【解决方案2】:

      for(each) 样式循环在底层使用迭代器,大多数情况下,除了通过迭代器对象的 remove() 方法之外,您无法编辑正在迭代的集合。为此,您必须明确使用迭代器。见this answer

      顺便说一句,带有大写首字符的变量名称可以工作,但会使人们更难阅读和理解您的代码。

      【讨论】:

        【解决方案3】:

        我不确定这是否是问题所在,但 ArrayList 不应该有索引的第一个参数和元素的第二个参数:

        public void add(int index, E元素) 你的代码是:

        stations.add(new RefillStation(int(random(0, width)), int(random(0, height))));
        

        它是先添加元素,然后指定索引。

        【讨论】:

          猜你喜欢
          • 2018-09-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-01-19
          • 2018-08-02
          • 2015-12-04
          • 1970-01-01
          相关资源
          最近更新 更多