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

查看:20
本文介绍了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天全站免登陆