screech43 - 10 months ago 40
Java Question

# Loops Practice with three parameters

I was given the following problem and am having difficulty. I defined the three variables, but using loops I am supposed to be able to make this work. Any help would be appreciated.

Distance runners build strength and stamina by running up hills. Here is an idea for a hill workout determined by three integer parameters: x, y and n. The third parameter, n, is the distance in miles from the bottom of the hill to the top. The runner starts at the bottom. The idea is to run up x miles and then immediately turn around and run down y miles, repeating this process until reaching the top. Write a program that prompts the user for x, y and n and then outputs the total distance that will be run during the workout, counting both the uphill parts and the downhill parts.

So, my general idea looks something like this. Note: Not tested.

``````public void runDistance(int x, int y, int n) {
int distanceRun = 0;
int elevation = 0;

//Takes us to one run shy of the top of the hill
while(elevation+(x) < n) {
elevation+=(x-y);
distanceRun+=x+y;
}

//adds the last bit of distance to the top of the hill (since we won't be running back down again)
//We don't want to add the full x distance because that might be more than the hill. We just want to add what's left.
if(elevation < n) {
distanceRun+=(n-elevation);
}

System.out.println("Total distance run: " + distanceRun);

}
``````