Home > Mobile >  Java Program to calculate how many bounces it will take a ball to drop in 5% decrements. User will i
Java Program to calculate how many bounces it will take a ball to drop in 5% decrements. User will i

Time:10-23

So I have to write a short Java program which will input of the height a ball is dropped from. Assuming that on each bounce the height reached reduces by 5%, output the number of bounces that occur before the ball stops bouncing.

I understand the logic of how to work this out but I cannot grasp how to put this into code.

I have some unfinished code, but just hit a brick wall. Any suggestions would be greatly appreciated.

package doWhileLoops;

import java.util.Scanner;

public class Ex3 {

    public static void main(String[] args) {
        Scanner key = new Scanner(System.in);
        int height = 0, noBounces = 0, fivePer = 0;
        fivePer = height /100 * 5;
        System.out.print("\n\tEnter the height in feet that the ball will be dropped from: ");
        height = key.nextInt();
        do {
            System.out.print("\n\tIt took  "   (height - fivePer));
            fivePer--;
        } while (height > 0);
    }
}

CodePudding user response:

Instead of calculating the five percent of the height and subtracting at the end, you can just decrease the height by 5% everytime until it reaches 0.

What about

float height = key.nextInt();
int nBounces = 0;
while(height > 0){
    height *= 5 / 100; //decrease the height by 5%
    nBounces  ; //add a bounce
}
System.out.print("\n\tIt took  "   nBounces);

Hope that helps!

CodePudding user response:

To get a feel of the algorithm, I mocked the following in Javascript. The important parts of the algorithm are:

  • height reduction of 5% is implemented as h = h * 95 / 100
  • there needs to be a terminating condition, i.e. threshold

When you run the algorithm you see that counter reaches 77. Why is it so high? Well, this is attributed to the fact that (1) a height reduction of 5% is unrealistic, in practice, a figure of 50% is more realistic, (2) in practical physics, there is a drag that causes it to diminish faster and eventually rest. With zero resistance, theoretically, something could bounce forever - hence, it is important that the question is improved with a terminating condition.

To demonstrate the algorithm, I did write it in Javascript not Java, so that you can run it in the browser.

let h = 50;        // initial height, say 50cm
let threshold = 1; // threshold height, say <= 1cm
let count = 0;     // counter for bounces
while (h > threshold) {
    h = h * 95 / 100; // 5% height reduction
    count  ;
    console.log(count, h);
}

  • Related