if语句在for循环中

时间:2012-06-28 22:16:52

标签: java if-statement for-loop

不工作

     int sum = 0;
          for (int index = 0; index < ratpop; index++) {


// verify whether population falls within blast radius
             if (xcord[index + 1] - xcord[index] <= str
                   || ycord[index + 1] - ycord[index] <= str) 

{
                // if it does sum population of both points
                sum += pop[index] + pop[index + 1];
             }
          }
          // prints out sum and the cordinates are not correct have to figure out
          // later
          System.out.println(xcord[1] + " " + ycord[0] + " " + sum);
       }
    }

我必须列出x坐标和y坐标之一的数组列表我对此声明的逻辑是,如果x cordinate或y cordinate小于变量str则求和,如果不是,但它不会这样做,它总结它无论如何。这是我原来的问题,但是没有任何可能阻止其他人发挥作用的额外内容,请提前感谢所有使这个网站变得优秀的爱好者,并为误解而道歉。

1 个答案:

答案 0 :(得分:1)

问题是您正在尝试访问超出数组边界的索引...

   for (int index = 0; index < ratpop - 1; index++) {

这将允许您访问[index + 1]而不会获得ArrayIndexOutOfBoundsException