如何在if语句中声明值? (在java中)

时间:2013-02-06 01:47:54

标签: java if-statement variable-declaration

所以这就是我到目前为止,我不知道为什么程序没有按照我想要的方式做出响应。继续显示“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);
}

5 个答案:

答案 0 :(得分:7)

我想你已经宣布了这样的avg2:double avg2;没有初始值。问题是,如果a == b == c例如,您的if条件都不是真的,avg2将不会被初始化。

  • 解决方案1:初始化avg2:double avg2 = 0;
  • 解决方案2(更好):使用if / else if / else语法而不是连续的ifs。如果有else,编译器将满足avg2将始终初始化。

答案 1 :(得分:0)

问题在于编译器看起来似乎有可能通过代码的路径,其中没有满足if语句条件。如果是这种情况,则不会对avg2进行任何分配。

答案 2 :(得分:0)

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

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

// now use can use avg2 here

答案 3 :(得分:0)

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

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);

答案 4 :(得分: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语句中初始化,最终可能不会发生......