Java:“局部变量可能未被初始化”不够智能? [英] Java: "Local variable may not have been initialized" not intelligent enough?

查看:243
本文介绍了Java:“局部变量可能未被初始化”不够智能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下方法:

void a ()
{
    int x;
    boolean b = false;
    if (Math.random() < 0.5)
    {
        x = 0;
        b = true;
    }
    if (b)
        x++;
}

x ++ 得到局部变量可能没有被初始化的错误。显然,x永远不会被初始化。有没有办法抑制警告,除非通过初始化x?谢谢。

On x++ I get the "Local variable may not have been initialized" error. Clearly x will never be used uninitialized. Is there any way to suppress the warning except by initializing x? Thanks.

推荐答案

不,没有办法 Java 程序的可能的代码路径来确定变量是否已经被初始化,所以它采取安全路由并警告你。

No, there is no way Java can examine all possible code paths for a program to determine if a variable has been initialized or not, so it takes the safe route and warns you.

不,你必须初始化你的变量来摆脱这个。

So no, you will have to initialize your variable to get rid of this.

这篇关于Java:“局部变量可能未被初始化”不够智能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆