Loopy wanderer: loops
Repeating actions in code.
We'll cover the following
Loops
To move the robot in five different directions, you probably had some code like this, repeated five times:
dir = randomGenerator.nextInt(4);robbie.setDirection(dir);maze.turn();
Is there a way to make Java do the same thing over and over again, so that we don’t have to type the same lines of code over and over again? Yes! The next code shows a programming construct called a for-loop that causes Java to execute the lines of code inside the braces of the loop 5 times:
class YellowBrick {public static void main(String[] args) {for(int i = 0; i < 5; i++) {System.out.println("Follow the yellow brick road.");}}}
Exercise: loopy wanderer
Write code to make the robot wander randomly for 20 turns.
import com.educative.robot.*;import java.util.Random;class LoopyWanderer {public static void main(String[] args) {// set up variables to store the robot and the mazeRobot robbie;Maze maze;Random randomGenerator = new Random();int dir;// create the robot and maze, and add// the robot to the mazerobbie = new Robot(3.0, 3.0, "red");maze = new Maze(8, 8, 50);maze.add(robbie);// your code here:}}