Why can't variables be declared in an if statement?

前端 未结 13 1827
感动是毒
感动是毒 2020-12-05 10:18

The following Java code does not compile.

int a = 0;

if(a == 1) {
    int b = 0;
}

if(a == 1) {
    b = 1;
}

Why? There can be no code pa

13条回答
  •  悲哀的现实
    2020-12-05 10:51

    int a = 0;
    
    if(a == 1) {
    int b = 0; // this int b is only visible within this if statement only(Scope)
    }
    
    if(a == 1) {
    b = 1; // here b can't be identify
    }
    

    you have to do following way to make correct the error

        int a = 0;
        int b = 0;
        if(a == 1) {
           b=0;
        }
        if(a == 1) {
            b = 1;
        }
    

提交回复
热议问题