Write a java program that runs a random horse race. The specification: There are
ID: 3554839 • Letter: W
Question
Write a java program that runs a random horse race. The specification: There are three horses. During each round, a random number from 1 to 100 is generated for each horse. The horse advances one square if the random number is greater than 50 Show the track like this:
1: -------- H ------|
2: ------- H -------|
3: --------- H ----- |
Write a method showHorse() that takes a horse number (1, 2 or 3), and shows the current position of the horse. Have the program run until one of the horses reaches the finish line - determine the winner. Must use threads for full credit. Output should be user friendly.
Explanation / Answer
public class HorseRace {
public static void main( String args[] )
{
Horse[] horse = new Horse[4];
for (int i=0; i<horse.length; i++) {
horse[i] = new Horse(i+1);
}
System.err.println( " Starting race" );
Horse.resetRace();
for (int i=0; i<horse.length; i++) horse[i].start();
Reporter rpt = new Reporter(horse);
rpt.start();
}
}
class Reporter extends Thread {
Horse[] horse;
public Reporter(Horse[] h) {
System.out.println("And they're off...");
horse = h;
}
public void run() {
System.out.print("Horse ");
for (int i=0; i<horse.length; i++) {
System.out.printf("%6d ", (i+1));
}
System.out.println();
while (!Horse.done()) {
System.out.print(" ");
System.out.print("Distance ");
for (int i=0; i<horse.length; i++) {
System.out.printf("%6d ", horse[i].getDistance());
}
}
System.out.print(" ");
System.out.print("Distance ");
for (int i=0; i<horse.length; i++) {
System.out.printf("%6d ", horse[i].getDistance());
}
System.out.println(" And the winner is "
+ Horse.getWinner());
}
}
class Horse extends Thread {
private static boolean raceOver = false;
private static final int raceLength = 100;
private static String winner = "";
private int distance;
private String name = "";
public Horse(int id) {
name = "Horsie #" + id;
distance = 0;
}
public static void resetRace() { raceOver = false; }
public static boolean done() { return raceOver; }
public static String getWinner() { return winner; }
public int getDistance() { return distance; }
public void run() {
while (!raceOver) {
try {
// get a little rest and then move
Thread.sleep((int)(Math.random() * 500));
if (++distance >= raceLength) raceOver = true;
} catch (InterruptedException e) {
System.err.println(e);
}
}
if (distance == raceLength) winner = name;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.