

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


// Exercise 7.41 Solution // Race.java // Program simulates the race between // the tortoise and the hare public class Race { static final int RACE_END = 70; static int tortoise = 1; static int hare = 1; public static void main( String args[] ) { int timer = 0; System.out.println( "ON YOUR MARK, GET SET" ); System.out.println( "BANG !!!!" ); System.out.println( "AND THEY'RE OFF !!!!" ); while ( tortoise != RACE_END && hare != RACE_END ) { moveHare(); moveTortoise(); printCurrentPositions(); ++timer; } if ( tortoise >= hare )
public static void moveTortoise() { int x = ( int ) ( 1 + Math.random() * 10 ); int tortoiseMoves[] = { 3, 6 }; if ( x >= 1 && x <= 5 ) // fast plod tortoise += tortoiseMoves[ 0 ]; else if ( x == 6 || x == 7 ) // slip tortoise -= tortoiseMoves[ 1 ]; else // slow plod ++tortoise;
if ( tortoise < 1 ) tortoise = 1; else if ( tortoise > RACE_END ) tortoise = RACE_END; } public static void moveHare() { int y = ( int ) ( 1 + Math.random() * 10 ); int hareMoves[] = { 9, 12, 2 }; if ( y == 3 || y == 4 ) // big hop hare += hareMoves[ 0 ]; else if ( y == 5 ) // big slip hare -= hareMoves[ 1 ]; else if ( y >= 6 && y <= 8 ) // small hop ++hare; else if ( y > 8 ) // small slip hare -= hareMoves[ 2 ]; if ( hare < 1 ) hare = 1; else if ( hare > RACE_END ) hare = RACE_END; } public static void printCurrentPositions() { for ( int count = 1; count <= RACE_END; count++ ) if ( count == tortoise && count == hare )
else if ( count == hare )
else if ( count == tortoise )
else
System.out.println(); } }