0

所以这就是我到目前为止所拥有的,我不知道为什么程序没有按照我想要的方式响应。不断显示“avg2 可能尚未初始化”。有任何想法吗??

if (a < b && a < c) {
    System.out.println("The lowest score was: " + a);
    System.out.println("The average without the lowest score is: " + ((b + c) / 2));
    avg2 = ((b + c) / 2);
}

if (b < a && b < c) {
    System.out.println("The lowest score was: " + b);
    System.out.println("The average without the lowest score is: " + ((a + c) / 2));
    avg2 = ((a + c) / 2);
}

if (c < a && c < b) {
    System.out.println("The lowest score was: " + c);
    System.out.println("The average without the lowest score is: " + ((a + b) / 2));
    avg2 = ((a + b) / 2);
}
4

5 回答 5

7

我想你已经像这样声明了 avg2:double avg2;没有初始值。问题是,a == b == c例如,如果您的任何 if 条件都不为真,并且avg2不会被初始化。

  • 解决方案1:初始化avg2:double avg2 = 0;
  • 解决方案 2(更好):使用 if / else if / else 语法代替连续的 if。如果有一个 else,编译器会满意 avg2 总是被初始化。
于 2013-02-06T01:50:42.413 回答
0

问题是编译器似乎有一条可能的路径通过代码,其中没有满足任何if语句条件。如果是这种情况,则永远不会对avg2.

于 2013-02-06T01:51:02.213 回答
0

因为编译器不知道 if 条件之一将评估为 true,因此avg2将被分配。一种解决方法是放置一个无条件的else

if (c < a && c < b) {
 ....
} else {
   throw new RuntimeException("Cannot be here");
}

// now use can use avg2 here
于 2013-02-06T01:51:22.163 回答
0

要修复“未初始化”错误,您应该将 3 个 if 语句重新排列到一个 if-else 块中。编译器不会测试 if 语句的条件是否为真,但是如果您在 if-else 块的每个部分内分配变量(必须包括“if all else failed” else),它将不可避免地被初始化。

double avg2;
if (a < b && a < c)
{
    System.out.println("The lowest score was: " + a);
    System.out.println("The average without the lowest score is: " + ((b + c) / 2));
    avg2 = ((b + c) / 2);
}else if (b < a && b < c)
{
    System.out.println("The lowest score was: " + b);
    System.out.println("The average without the lowest score is: " + ((a + c) / 2));
    avg2 = ((a + c) / 2);
}else {
    System.out.println("The lowest score was: " + c);
    System.out.println("The average without the lowest score is: " + ((a + b) /2));
    avg2 = ((a + b) / 2);
}

执行此过程的更好方法:

double avg2;
double lowest = a;
if(lowest > b)
    lowest = b;
if(lowest > c)
    lowest = c;
System.out.println("The lowest score was: " + lowest);
avg2 = (a + b + c - lowest)/2;
System.out.println("The average without the lowest score is: " + avg2);
于 2013-02-06T02:00:17.467 回答
0

那段代码伤害了我的眼睛,我觉得有必要发布这个答案:)

double lowest = Math.min(Math.min(a, b), c);
double avg2 = (a + b + c - lowest) / 2;
System.out.println("The lowest score was: " + lowest);
System.out.println("The average without the lowest score is: " + avg2);

只有 4 行而不是 15 行,并且此代码不会生成该警告,因为正在初始化变量。

可能警告是因为变量在 if 语句中被初始化,最终可能不会发生......

于 2013-02-06T02:30:47.457 回答