【问题标题】:Why doesn't my bouncy ball program stop after the 5th bounce?为什么我的弹力球程序在第 5 次反弹后没有停止?
【发布时间】:2014-10-07 18:05:58
【问题描述】:

我在一段时间内嵌套了一个 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);
            }
        }
    }
}

【问题讨论】:

    标签: java loops for-loop while-loop


    【解决方案1】:

    在时间增加 30 倍之前,您不会到达外部 while 循环。您可以将反弹要求添加到 for 循环并删除 while 循环。发生的情况是,在外部 while 循环中检查反弹之前,您可以在 for 循环中反弹 30 次。

        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

    【讨论】:

      【解决方案2】:

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

      if (height < 0)
      

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

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

      【讨论】:

      • 但是 vel 也可以是负数,所以高度也可以,不是吗?
      • 速度可以是负数,但是我假设高度不会是负数,因为这意味着它在地面以下,因此永远不会达到这个 if 语句。
      • 高度可以是负数。尝试使用 16 作为速度并运行 4 个循环。
      • 我想我最初的假设是与高度进行比较的起始参考点是球弹跳的地面(高度 = 0)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-29
      相关资源
      最近更新 更多