为什么我的弹力球计划在第5次弹跳后没有停止?

时间:2014-10-07 18:05:58

标签: java loops for-loop while-loop

我在一段时间内嵌套了一个for循环以跟踪时间。如果满足某个条件,while循环会跟踪反弹。只要满足该条件,for循环将继续计数。但是一旦满足条件,循环就会停止。但是,无论while循环内的条件如何,它都会继续。

/*
     * @Author Lawton C Mizel
     * @Version 1.0, 07 October 2014
     * 
     * A program that simulates a ball bouncing by computing 
     * its height in feet and each "second" as time passes on 
     * a simulated clock.
     * 
*/
public class bouncyballs001 {
    public static void main(String[] args) {

        // create and connect scanner object
        Scanner keyboard = new Scanner(System.in);

        //introduce program
        System.out.println("Welcome to the bouncing ball program!");

        //prompts the user
        System.out.println("Please enter the initial velocity: ");

        double vel = keyboard.nextInt();

        //initial variables

        double height = 0;
        int bounce = 0;
        while (bounce < 5) {
            for (int time = 0; time <= 30; time++) //counter
            {
                if (time >= 0) {
                    height = height + vel;
                    vel = vel - 32.0;
                }

                if (height < 0) {
                    height = height * -0.5;
                    vel = vel * -0.5;
                    System.out.println("BOUNCE!");
                    bounce++;
                }
                System.out.println("time: " + time + " " + "height: " + height);
            }
        }
    }
}

2 个答案:

答案 0 :(得分:3)

在时间增加30次之前,你没有到达外部while循环。您可以将反弹要求添加到for循环并删除while循环。发生了什么事情,你可以在for循环中反弹30次,然后在外部while循环中检查反弹。

    for(int time=0; time <= 30 && bounce < 5; time++) //counter, bails out if bounce > 5
    {
        if(time >= 0)
        {
        height = height + vel;
        vel = vel - 32.0;
        }

        if(height < 0)
        {
            height = height * -0.5;
            vel = vel * -0.5;
            System.out.println("BOUNCE!");
            bounce++;
        }
        System.out.println("time: "+time+" "+"height: "+height);
    }

或者,您可以使用if语句和break

答案 1 :(得分:1)

你在一个永远不会被调用的条件中弹跳++。

if (height < 0)

永远不会是真的,因为高度从0开始上升(即永远不会是负数)。

这意味着弹跳永远不会是0。