LAB 8 - Introduction to Programming (part 3 - turtles)

Lab Exercises

Topics

n      To create a method to reuse a series of Java statements

n      To be able to use methods to perform tasks

n      To be able communicate with methods

 

Exercises

3.5 Creating Methods

 

Type in the following program shell:

 

/* Program that displays different figures using turtle graphics

 * World and Turtle classes are defined in bookClasses developed

 * at Georgia Tech by Mark Guzdial / Barbara Ericson

 *

 * @author Wayne Summers

 * @date   Sept. 4, 2007

 */

 

public class TryTurtles

{

  public static void main(String[] args)

  {

    World newWorld;

    Turtle myTurtle;

   

    newWorld = new World();

   

    myTurtle = new Turtle (newWorld);  

  }

}

 

Compile and run the program.

 

3.5.1 Methods that Take Input

Type in the following method between the bottom two braces:

static void drawSquare(Turtle turtle1)

  {

    turtle1.turnRight();

    turtle1.forward(30);

    turtle1.turnRight();

    turtle1.forward(30);

    turtle1.turnRight();

    turtle1.forward(30);

    turtle1.turnRight();

    turtle1.forward(30);

  }

 

Compile and run the program.

 

Type the following statement in the main method below the creation of myTurtle.

 

    drawSquare(myTurtle);

 

Change the drawSquare method to look like:

  static void drawSquare(Turtle turtle1, int width)

  {

    turtle1.turnRight();

    turtle1.forward(width);

    turtle1.turnRight();

    turtle1.forward(width);

    turtle1.turnRight();

    turtle1.forward(width);

    turtle1.turnRight();

    turtle1.forward(width);

  }

 

and change the call to   

            drawSquare(myTurtle, 30);

 

QUESTIONS:

  1. Modify your program to draw four squares of different sizes and colors in four different locations of the world. [Don’t forget to pick up the pen before you move the turtle and to hide the turtle when you are finished]

 

Submit the answers through the DropBox in WebCT.