Search code examples
javaif-statementgridworld

"GridWorld" for ThinkJava Exercise 5.1


Newbie completeing thinkJava book and trying to figure out one of the answers to the exercises. It calls for me to download the "GridWorld" files and complete the following steps:

  1. Write a method named moveBug that takes a bug as a parameter and invokes move. Test your method by calling it from main.
  2. Modify moveBug so that it invokes canMove and moves the bug only if it can.
  3. Modify moveBug so that it takes an integer, n, as a parameter, and moves the bug n times (if it can).
  4. Modify moveBug so that if the bug can’t move, it invokes turn instead.

I am stuck on number 3, I can not figure out how to pass n into the "move() method"

-Please Help I am a newbie

My Code:

import info.gridworld.actor.ActorWorld;
import info.gridworld.actor.Bug;
import info.gridworld.actor.Rock;

public class BugRunner
{
    public static void main(String[] args)
    {
        ActorWorld world = new ActorWorld();
        Bug redBug = new Bug();
        world.add(redBug);
        world.add(new Rock());
        world.show();
        moveBug(redBug,5);
        System.out.println(redBug.getLocation());
    }

    public static void moveBug(Bug aBug, int n){
        if(aBug.canMove() == true){
        aBug.move();
        } else {
        aBug.turn();
        }
    }


}

Solution

  • Thanks for pointing me @Andreas My Solution that worked:

    public static void moveBug(Bug aBug, int n){
        for(int i = 0; i < n; i++){
            if(aBug.canMove())
               {
               aBug.move();
               } else {
               aBug.turn();
               }
           }
       }