Java if语句中的值未初始化

Java if语句中的值未初始化,java,Java,以下代码有一个编译器错误: speedMsg可能未初始化 我怎样才能解决这个问题 String speedMsg; // Determine the grade if (speed >= 150) speedMsg = "STOP! STOP! Please let me OUT!"; else if (speed <= 150) speedMsg = "Whew I'll just walk from here Thanks."; stringspeedmsg; //定

以下代码有一个编译器错误:

speedMsg可能未初始化

我怎样才能解决这个问题

String speedMsg;

// Determine the grade
if (speed >= 150)
  speedMsg = "STOP! STOP! Please let me OUT!";
else if (speed <= 150)
  speedMsg = "Whew I'll just walk from here Thanks.";
stringspeedmsg;
//定级
如果(速度>=150)
speedMsg=“停下!停下!请放我出去!”;
否则,如果(速度更改为:

// Determine the grade
if (speed >= 150)
    speedMsg = "STOP! STOP! Please let me OUT!";
else
    speedMsg = "Whew I'll just walk from here Thanks.";

这应该足以让编译器确保变量将被初始化。

else if
替换为
else
,因为编译器将知道speedMsg将始终有一个值。

请初始化speedMsg:

String speedMsg = null;

这应该可以解决问题,speedMsg可能没有初始化。

您必须包含一个
else
语句,因为编译器不够聪明,无法判断您是否在
if
if else
语句中包含了所有可能的
speed

请注意,局部变量是唯一没有默认值的变量,您需要初始化它们。

设置:

String speedMsg = "";
或者删除else(如果),将其更改为else

if (speed >= 150)
    speedMsg = "STOP! STOP! Please let me OUT!";
else
    speedMsg = "Whew I'll just walk from here Thanks.";
更好的是:

String speedMsg = speed >= 150 ? 
                    "STOP! STOP! Please let me OUT!" :
                    "Whew I'll just walk from here Thanks.";

您没有初始化字符串,然后试图返回它。

如果
速度>=150
速度
错误变量speedMsg可能未初始化

此错误消息告诉您,变量(此处:speedMsg)可能为null。因此,如果您设置如下默认值,则可以解决此问题:

String speedMsg = "Speed";
或者你就这样修好它

if (speed >= 150)
    speedMsg = "STOP! STOP! Please let me OUT!";
else
    speedMsg = "Whew I'll just walk from here Thanks.";
您得到该消息的原因是,eclipse无法检查“if-else-if”块中的比较是否有效,并且将始终设置speedMsg(无默认设置)


第二种解决方案更优雅。

编译器不知道if-elseif覆盖整个域。因此,is警告说,除非您指定初始值或“else”块,否则返回值可能为空。注意@DuncanJones,感谢您没有向下投票。冲动回答。;+1。目前,
else if
表示两个条件都不可能命中,因此变量可能未初始化。因为很明显,必须达到某个条件或其他条件,所以在代码中明确这一点是没有问题的。这个解决方案帮了我很大的忙,我很高兴看到这个网站,因为我的导师不擅长解释这一点。非常感谢