Java Array List / while循环计数错误

时间:2017-01-11 18:42:50

标签: java arraylist while-loop

我遇到的问题是我的while循环结束了,虽然它只执行了一次我的错误?

public class ear {

    private ArrayList<Point> Master = new ArrayList<Point>();
    private ArrayList<Point> Shot = new ArrayList<Point>();

    public ear() {
        addMaster();
        addShot();
        if (Shot.get(0).y == Master.get(0).y) {
            while (Shot.get(0).x > Master.get(0).x) {
                System.out.println("MasterY: " + Master.get(0).x);
                System.out.println("ShotY: " + Shot.get(0).x);
                moveShot();
            }
        }
    }

    public void moveShot() {
        Point p = new Point();
        for (int i = 0; i < Shot.size(); i++) {
            Shot.get(i).x = p.x;
            p.x -= 10;
            p.y = 5;
            Shot.set(i, p);
        }
    }
}   

在主类中创建耳朵的对象 在移动镜头中,我获得镜头值x并减去其中的10。

2 个答案:

答案 0 :(得分:1)

1)这是无用的,因为它总是如此:

 if (Shot.get(0).y == Shot.get(0).y) 

2)在将Point p = new Point(); Shot.get(i).x = p.x;分配给Point时,Shot.get(i).x没有任何意义。如果您希望使用中间值Point来存储当前Shot并更改其值,则应该采取相反的措施:

p.x = Shot.get(i).x - 10;
p.y = Shot.get(i).y + 5;

然后将p设置为当前Shot的新值:

 Shot.set(i, p);

3)最后,如果xyShot的公开字段,您可以直接更改它们,而无需使用中间Point对象:

public void moveShot() { 
    for (int i = 0; i < Shot.size(); i++) {
        Shot.get(i).x -= 10;
        Shot.get(i).y += 5;
    }
}

不建议使用实例公共字段,但在游戏中有时会使用它。

答案 1 :(得分:0)

moveShot()方法中,您创建的Point(默认情况下)位于(0, 0) 然后,遍历所有Shots,将其x值设置为0.然后,x值不再大于Master x值,因此循环结束

相关问题