Java Genesis

Hints for Chapter 6: Control Constructs

Problem 16: flashing colours

Here is the complete code for the modified version of the class FlashingColours making use of a switch-statement rather than nested if-else statements:


   import genesis.*;
   import java.awt.*;

   public class FlashingColours {
	
	/*
	Flashing the colours of a circle.
	*/
	
	public static void main (String [] args) {
	   CircleFigure.create();
	   CircleFigure.setRadius(100);
	   int rand;
	   while (true) {
		Delay.milliseconds(250);
		rand = (int)(5*Math.random());
		switch (rand) {
		   case 0: CircleFigure.setColour(Color.red); break;
		   case 1: CircleFigure.setColour(Color.blue); break;
		   case 2: CircleFigure.setColour(Color.green); break;
		   case 3: CircleFigure.setColour(Color.magenta); break;
                   default: CircleFigure.setColour(Color.yellow);  
		}
	   }
	}
   }