How to make loop end once the last element in the array meets condition?
In my bouncing ball program, it asks the user to insert a number of balls which will be displayed on the screen and will start at the top of the canvas then drop and bounce on a line on the bottom of the canvas.
When finished = true, the animation will stop. So far the animation stops once the X position of the first ball goes past 550. How do I make the animation end once the X position of EVERY ball is more than 550?
public void multiBounce(int numBalls)
{
    BouncingBall[] balls;
    balls = new BouncingBall[numBalls];
    int x = 50;
    int y = 150;
    for (int i = 0; i < balls.length; i++){
          balls[i] = new BouncingBall(x, y, 16, Color.blue, ground, myCanvas);
          x = x + 20;
          y = y - 30;
          balls[i].draw();  
    }
    boolean finished =  false;
    while(!finished) {
     for (int i = 0; i < balls.length; i++){
           balls[i].move();
    }
     for (int i = 0; i < balls.length; i++){
         if (balls[i].getXPosition() >= 550){
             finished = true;
        }
    }
}
Just check for every ball whether it is beyond your desired position. This code snippet should do the work. Just replace the last for loop by the code below.
finished=true;
for (int i = 0; i < balls.length; i++){ 
    if (balls[i].getXPosition() >= 550){  
        finished = finished && true; }
    else{
        finished=false;
        break;
    } 
}
 You should use a break statement.  When its encountered inside a loop , the loop is immediately terminated and the program control resumes at the next statement following the loop .  For more details see Branching Statements  
public void multiBounce(int numBalls)
    {
        BouncingBall[] balls;
        balls = new BouncingBall[numBalls];
        int x = 50;
        int y = 150;
        for (int i = 0; i < balls.length; i++){
            balls[i] = new BouncingBall(x, y, 16, Color.blue, ground, myCanvas);
            x = x + 20;
            y = y - 30;
            balls[i].draw();
        }
        boolean finished =  false;
        while(!finished) {
            for (int i = 0; i < balls.length; i++){
                balls[i].move();
            }
            for (int i = 0; i < balls.length; i++){
                if (balls[i].getXPosition() < 550){
                    finished = false;
                    break;
                }
                else {
                    finished = true;
                }
            }
            }
        }
上一篇: CSS不能很好地显示字体
