Write a method ant that simulates an ant trying to crawl up a building of height
ID: 660785 • Letter: W
Question
Write a method ant that simulates an ant trying to crawl up a building of height 6 steps. The ant starts on the ground, at height 0. Each iteration, the ant either crawls up one step, or slips off and falls all the way back to the ground. There is a 50% chance on each iteration that the ant will slip. You should use a Random object for this where zero represents a slip. The method should keep going until the ant gets to the top of the building. It should then print out the number of falls that the ant took before it finally reached the top.
Here is a sample execution.
(Because this problem uses random numbers, our test cases check only the general format of your output. You must still examine the output yourself to make sure the answer is correct.)
Method problem: For this problem, you are supposed to write a Java method as described. You should notwrite a complete Java class; just write the method(s) described in the problem statement.
Explanation / Answer
public class AntClimb {
public static void main(String[] args)
{
final int MAX_HEIGHT = 6;
int height = 0;
int numFalls = 0;
while (height < MAX_HEIGHT) // while the ant has not reached the 6th step
{
rand = (int)(Math.random() * 2); // stores a random value of 0 or 1 as rand
if(rand == 0) // rand = 0 implies the ant slides back down
{
height = 0;
numFalls++;
}
else // else, rand = 1 and implies the ant climbs up one stair
{
height++;
}
}
System.out.println(
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.