我正在编写一个程序来确定乌龟,野兔,狼和绵羊之间的种族胜利者。比赛分为10个时间步(0-9)。每个参与者以不同的速度移动。我需要输出每一方的总距离并宣布获胜者,如果有平局,我可以选择任何并列方作为获胜者输出。
我的问题来自我声明数组“数组”的部分,如果确定获胜者则使用if else。我得到的错误信息是说变量“赢家”尚未初始化。我假设这是因为我没有正确比较数组条目,并且没有if语句返回true值。我的目标是将数组按升序排序,然后取最高值(行进的最远距离)并使用==运算符确定它由(野兔,乌龟,绵羊,狼)代表的变量。我做错了什么?
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;
}
}
答案 0 :(得分:1)
问题是您使用了一堆没有结尾if-else
阻止的else
语句。
基本上,您需要为winner
提供默认值,因为在当前代码中,如果array[0]
没有匹配任何内容,则永远不会设置winner
。
或者,您可以在代码中添加else
块,以便初始化winner
。
另一种解决方案:将if-else
的最后一个块更改为else
。这使得最后一种情况成为默认情况。
例如:
String winner = "default"; // this can be anything you want as long as it's not null
或
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";
else winner = "default case"
或
if (array[0] == hare)
winner = "hare";
else if (array[0] == tortoise)
winner = "tortoise";
else if (array[0] == sheep)
winner = "sheep";
else winner = "wolf";
// the logic still works here - if it wasn't the hare, tortoise or sheep it must be the wolf