简体   繁体   中英

Make variable visible outside loop

I'm new to java, im just getting used to it. I don't know how to make a variable seen outside a if statement. In one of my methods, I created an array inside a if statement and want it to be seen outside the if statement too. I don't seem to know how to do this. I tried the following but it is not working.

You can change

 if(i==1){
  int[] temp; // this temp array visible only inside if
  temp = new int[7];
 }
 temp[i] = temperature;

To

 int[] temp=null; // initialize temp array out side if
 if(i==1){       
   temp =new int[7] 
 }
 temp[i] = temperature;

In second case temp is define out side the if , So your temp array visible inside for loop.

Edit: Read About variable scope . You can find more info here .

Declare the variable in the "scope" you want it to be available for edit/read.

If you want it to be available outside of the if statement as well, then declare it at the beginning of the method (outside if statement).

public void readTemperature(int i, int temperature) {
     int[] temp = null; 
       // temp variable will be available in "smaller scopes" anywhere inside 
       // the method even within control logic statement (if else) or loops such as 
       // for/while
     if(i==1){       
         temp =new int[7] 
     }
     if (temp != null) // you may want to add this check
         temp[i] = temperature;
     }
 }

Not completely related but this might help article to read.

You must define the array from outside the if statement. You can follow both ways.

int[] temp = null; 
if(i==1){       
    temp =new int[7] 
}


int[] temp; 
if(i==1){       
    temp =new int[7] 
}

first one must be null check before use it. second one gives compiler error to initialize. So you can add else clause and set empty array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM