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

前端 未结 3 1945
醉酒成梦
醉酒成梦 2020-12-17 03:49

Consider the following method:

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


        
相关标签:
3条回答
  • 2020-12-17 04:09

    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 
        }
    }
    
    0 讨论(0)
  • 2020-12-17 04:11

    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.

    0 讨论(0)
  • 2020-12-17 04:15

    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.

    0 讨论(0)
提交回复
热议问题