44.8k views
3 votes
Which method implements walkToWall correctly?

A) karel.faceEast();
while( karel.isFrontClear() )
{
move();
}
B) karel.faceEast();
while( karel.isFrontClear() )
{
karel.turnLeft();
}
C) karel.faceEast();
while( !karel.isFrontClear() )
{
karel.turnLeft();
}

User Make Mark
by
8.0k points

1 Answer

3 votes

Final answer:

The correct method to implement walkToWall is Option A, where Karel faces East and moves until a wall is encountered. The other options either result in Karel spinning in place or getting stuck in an infinite loop.

Step-by-step explanation:

The correct method that implements walkToWall would be the one that moves Karel until a wall is encountered, assuming that Karel is a robot in a grid-based environment, such as in an introductory programming exercise. The options provided suggest actions that Karel should take. Let's analyze each one:

  • Option A: Karel is turned to face East, and then a while loop is used to move Karel forward as long as there is no wall directly in front. This seems to follow the expected behavior of the function walkToWall.
  • Option B: In this scenario, Karel faces East, but then the while loop includes only a turn action, specifically turning left. This would result in Karel spinning in place rather than moving towards a wall.
  • Option C: Here, Karel also faces East, but the while loop is checking for the wall being present, which is the opposite of what we want. The loop will continue infinitely if there is a wall because there is only a turn action within the loop.

Therefore, the correct implementation that matches the walkToWall method is Option A: Karel faces East and moves forward as long as there is no wall blocking the path.

User Chris Bode
by
7.6k points