Program branching based on certain conditions is part of the default structures of each programming language. The actions after if are only executed if the conditions are meet. Otherwise the actions after else are executed.
//Tu5.java import ch.aplu.turtle.*; import java.awt.Color; public class Tu5 { Turtle joe = new Turtle(); public Tu5() { joe.setPos(-200, -200); joe.setLineWidth(5); for (int i = 0; i < 10; i++) { if (i % 2 == 0) joe.setPenColor(Color.red); else joe.setPenColor(Color.green); joe.fd(40).rt(90).fd(40).lt(90); } } public static void main(String[] args) { new Tu5(); } } |
double a = Math . random () ; |
The method Math.random () generates a random multi-digit decimal number between 0 and 1 (e.g. 0.48245923) |
if ( a > 0 . 5 ) |
The conditions are defined by logical operators (boolean operators): >, >= , < , <= , == , != |
//Tu6.java import ch.aplu.turtle.*; import java.awt.Color; public class Tu6 { Turtle t = new Turtle(); public Tu6() { t.addStatusBar(20); t.speed(-1); t.setPenColor(Color.red); for (int s = 4; s < 200; s = s + 2) { if (s == 140) t.setPenColor(Color.green); t.forward(s); t.right(90); t.setStatusText("Size: " + s); } } public static void main(String[] args) { new Tu6(); } } |
i % 2 | Besides the default arithmetic operations +, -, * and / the so called modulo division % can be used. It returns the remainder of a division. |
if (i % 2 == 0) |
The conditions are defined by logical operators (boolean operators): >, >= , < , <= , == , != Be sure that the logical operator == is always written with two equal signs. |
joe. penUp () | The Turtle does not draw, but still moves according to the program statements. |
joe. penDown () | The Turtle draws again. |
//Tu7.java import ch.aplu.turtle.*; import java.awt.Color; public class Tu7 { Turtle joe = new Turtle(); public Tu7() { joe.hideTurtle(); joe.clear(Color.black); joe.setLineWidth(4); for (int i = 0; i < 120; i++) { if (i % 3 == 0) joe.setPenColor(Color.red); else if (i % 3 == 1) joe.setPenColor(Color.green); else joe.setPenColor(Color.magenta); joe.forward(150); joe.back(150); joe.left(3); } } public static void main(String[] args) { new Tu7(); } } |
joe.hideTurtle() | The Turtle becomes invisible. This enables it to move and draw faster |