Part A

(a) Write the simulate method, which simulates the frog attempting to hop in a straight line to a goal from the frog's starting position of 0 within a maximum number of hops. The method returns true if the frog successfully reached the goal within the maximum number of hops; otherwise, the method returns false. The FrogSimulation class provides a method called hopDistance that returns an integer representing the distance (positive or negative) to be moved when the frog hops. A positive distance represents a move toward the goal. A negative distance represents a move away from the goal. The returned distance may vary from call to call. Each time the frog hops, its position is adjusted by the value returned by a call to the hopDistance method. The frog hops until one of the following conditions becomes true: • The frog has reached or passed the goal. • The frog has reached a negative position. • The frog has taken the maximum number of hops without reaching the goal

Intent: Simulate the distance traveled by a hopping frog +1 Calls hopDistance and uses returned distance to adjust (or represent) the frog’s position +1 Initializes and accumulates the frog’s position at most maxHops times (must be in context of a loop) +1 Determines if a distance representing multiple hops is at least goalDistance +1 Determines if a distance representing multiple hops is less than starting position +1 Returns true if goal ever reached, false if goal never reached or position ever less than starting position

public class FrogSimulation
{
 
    public boolean simulate() {
        int distance = 0;
        for(int i=0; i<maxHops; i++) {
            distance += hopDistance();
            if(distance<goalDistance){
                return false;
            }
            if(distance>=goalDistance){
                return true;
            }
        }
    }
    return false;
    }

Part B

Complete method simulate below. You must use hopDistance appropriately to receive full credit.

  • Simulates a frog attempting to reach the goal as described in part (a).
  • Returns true if the frog successfully reached or passed the goal during the simulation;
  • false otherwise.
public class FrogSimulation
{ 
    public boolean simulate() {
    int distance = 0;
    int goal = goalDistance;
    
    for(int i=0; i<maxHops; i++) {
        distance += hopDistance();
        if(distance>=goalDistance){
            return true;
        }
        else {
            return false;
        }
}