简体   繁体   English

Java不会完全遍历数组

[英]Java not iterating all the way through array

I have 5 rectObj yet the loop is only continuing twice. 我有5个rectObj,但循环仅持续了两次。

Here's my code: 这是我的代码:

public boolean bottomLeft() {
    boolean ret = false;
    Iterator<rectObj> rectItr = Main.rectAr.iterator();
    while (rectItr.hasNext() && ret == false) {
        rectObj e = rectItr.next();
        if (x > e.getX() && x < e.getX()+e.getWidth()
                && y+h > e.getY() && y+h < e.getX()+e.getHeight()) {
            ret = true;
        }else{
            if(rectItr.hasNext()) {
                rectItr.next();
            }
        }
    }
    return ret;
}

rectObj rect1 = new rectObj(250,250,50,50);
    rectObj rect2 = new rectObj(0,440,500,50);
    rectObj rect3 = new rectObj(0,0,500,50);
    rectObj rect4 = new rectObj(400,200,50,50);
    rectObj rect5 = new rectObj(0,200,50,50);

    rectAr.add(rect1);
    rectAr.add(rect2);
    rectAr.add(rect3);
    rectAr.add(rect4);
    rectAr.add(rect5);

I want the loop to continue throughout all of the array unless it finds an object that it has collided with. 我希望循环在整个数组中继续进行,除非找到与之碰撞的对象。

Thanks for any replies! 感谢您的任何答复!

You're calling rectItr.next() a second time in the else part inside the loop. 您正在循环内的else部分中第二次调用rectItr.next() Try removing the else part of the if-else statement. 尝试删除if-else语句的else部分。

The else part is checking if rectItr.hasNext() and if it has, it is calling rectItr.next() . else部分正在检查rectItr.hasNext()是否存在,是否正在调用rectItr.next() Then it returns to the top of the while loop which is doing the same thing again. 然后返回到while循环的顶部,该循环再次执行相同的操作。 Therefore, each loop, if the if test is false, then it calls rectItr.next() an extra time, and skips the next element in the array. 因此,在每个循环中,如果if测试为false,则它将额外调用rectItr.next() ,并跳过数组中的下一个元素。

@Dermot is correct. @Dermot是正确的。

You can actually simplify and reformat the method as follows: 您实际上可以简化并重新格式化该方法,如下所示:

public boolean bottomLeft() {
    for (rectObj e : Main.rectAr) {
        if (x > e.getX() 
                && x < e.getX() + e.getWidth()
                && y + h > e.getY() 
                && y + h < e.getX() + e.getHeight()) {
            return true;
        }
    }
    return false;
}

... and this reveals that there is ANOTHER bug in your method. ...这表明您的方法中存在另一个错误。 This line 这条线

      && y + h < e.getX() + e.getHeight()

... should be ... ... 应该 ...

      && y + h < e.getY() + e.getHeight()

... I think. ... 我认为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM