I am writing a program to determine the winner of a race between a tortoise, hare, wolf, and sheep. The race is divided into 10 time steps (0-9). Each participant moves at a different rate. I need to output the total distance traveled by each party and declare a winner, and if there is a tie I can choose any of the tied parties to output as the winner.
My problem is coming from the part where I declare the Array "array" and use if else if to determine the winner. The error message I'm getting is saying the variable "winner" has not been initialized. I assume this is because I'm not comparing the array entries correctly and none of the if statements are returning a true value. My goal was to sort the array into ascending order, then take the highest value (the farthest distance traveled) and figure out which variable it is represented by (hare, tortoise, sheep, wolf) by using the == operator. What am I doing wrong?
import java.util.*;
public class Hw3pr5 {
public static void main(String[] args) {
double hare = 0, tortoise = 0; //these variables will hold the total
double sheep = 0, wolf = 0; //distance covered by each racer
String winner;
for (int index = 0; index < 10; index++) {
hare = hareTimeStep(index, hare);
tortoise = tortoiseTimeStep(index, tortoise);
sheep = sheepTimeStep(index, sheep);
wolf = wolfTimeStep(index, wolf);
}
double[] array = {
hare, tortoise, sheep, wolf
};
Arrays.sort(array);
if (array[0] == hare)
winner = "hare";
else if (array[0] == tortoise)
winner = "tortoise";
else if (array[0] == sheep)
winner = "sheep";
else if (array[0] == wolf)
winner = "wolf";
System.out.println("The race is over. The hare traveled " + hare +
" miles.\nThe tortoise traveled " + tortoise +
" miles.\nThe sheep traveled " + sheep + " miles.\nThe " +
"wolf traveled " + wolf + " miles.\nThe grand winner: the " +
winner + "!");
}
public static double hareTimeStep(int timestep, double distance) {
Random rnd = new Random();
double progress = 0;
if (timestep < 2)
progress = 13 + rnd.nextDouble() * 4;
distance += progress;
return distance;
}
public static double tortoiseTimeStep(int timestep, double distance) {
Random rnd = new Random();
double progress = 2 + rnd.nextDouble() + rnd.nextDouble();
distance += progress;
return distance;
}
public static double sheepTimeStep(int timestep, double distance) {
Random rnd = new Random();
double progress = 0;
if (timestep % 2 == 0)
progress = 6 + 4 * rnd.nextDouble();
else
progress -= 2;
distance += progress;
return distance;
}
public static double wolfTimeStep(int timestep, double distance) {
Random rnd = new Random();
double progress;
if (timestep % 3 == 0)
progress = 0;
else
progress = 4 + rnd.nextDouble();
distance += progress;
return distance;
}
}
String winner;toString winner = "";, but I wonder if you have more severe problems. What if hare == tortoise? Who is the winner?winnervariable because it may not get initialized in your code, depending on what the value ofarray[0]is.