Java: “Local variable may not have been initialized” not intelligent enough?

故事扮演 提交于 2019-11-29 04:44:54

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.

Denys Séguret

There is one :

void a () {
    if (Math.random() < 0.5) {
        int x = 1;
    }
}

The compiler isn't responsible for devising and testing the algorithm. You are.

But maybe you should propose a more practical use case. Your example doesn't really show what's your goal.

Why don't you simply use

void a ()
{
    int x;
    boolean b = false;
    if (Math.random() < 0.5)
    {
        x = 0;
        b = true;
        x++;
    }
    if (b) {
        //do something else which does not use x
    }
}

In the code why do you want to use x outside the first if block, all the logic involving x can be implemented in the first if block only, i don't see a case where you would need to use the other if block to use x.

EDIT: or You can also use:

void a ()
{
    int x;
    boolean b = (Math.random() < 0.5);
    if (b) {
         x=1
        //do something 
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!