Turtlegraphics with Java
HomeAufgabenDruckenJava-Online

for-structure (Iteration)

Most cases of repetitions only need a repetition counter or loop counter. The next example displays how the while-structure can be replaced by a simple for-structure, or for-loop.


// Tu3.java

import ch.aplu.turtle.*;

public class  Tu3
{
  Turtle joe = new Turtle();

  public Tu3()
  {
    for (int = 0; i < 9; i++)
    {
      joe.forward(160);
      joe.right(160);
    }
  }

  public static void main(String[] args)
  {
    new Tu3();
  }
}
 

Nesting for-loops

for-loops can be nested. In the example Tu4.java the inner loop draws a square each of the ten times it is called from the outer loop.
The example Tu4a.java uses nested for-loops to draw a swiss flag.


// Tu4.java

import ch.aplu.turtle.*;

public class  Tu4
{
  Turtle joe = new Turtle();

  public Tu4()
  {
    joe.speed(500);
    for (int = 0; k < 10; k++)
    {
      for (int = 0; i < 4; i++)
      {
        joe.forward(80);
        joe.right(90);
      }
      joe.left(36);
    }
  }

  public static void main(String[] args)
  {
    new Tu4();
  }
}
 

 

// Tu4a.java

import ch.aplu.turtle.*;
import java.awt.Color;

public class  Tu4a
{
  Turtle joe = new Turtle();

  public Tu4a()
  {
    joe.setPos(-5050);
    joe.setColor(Color.red);
    joe.setPenColor(Color.red)
    for (int k = 0; k < 4; k++)
    {
      for (int i = 0; i < 3; i++)
      {
        joe.forward(100);
        joe.right(90);
      }
      joe.left(180);
    }
    joe.setFillColor(Color.red);
    joe.fill(-6060);
    joe.hideTurtle();
  }

  public static void main(String[] args)
  {
    new Tu4a();
  }
}
 

 

Explaining the program code:

import  java.awt.Color ; This import is necessary if working with colors.
joe.setColor (Color.red) ; The Turtle itself is colored red.
joe. setPenColor (Color.red) ; The Turtle draws red lines.
joe. setFillColor (Color.red) ; The filling color is set to red.
joe. fill ( - 60 ,  60 ) ; The area in which the coordinates lie is being filled.
joe.hideTurtle(); The Turtle is hidden (invisible).


Colors

Default colors can be called by using the command "Color.color" e.g. Color.blue, Color.pink etc. E.g.:
joe.setColor(Color.magenta);

It is also possible to define any other color by choosing the amount (between 0 and 255) of red, green and blue. E.g.:

Color c = new Color(120, 200, 80);
joe.setColor(c);