使变量可见外部循环

时间:2014-10-06 04:14:40

标签: java

我是java的新手,我只是习惯了它。我不知道如何在if语句之外看到变量。在我的一个方法中,我在if语句中创建了一个数组,并希望它在if语句之外也可以看到。我似乎不知道该怎么做。我试过以下但是没有用。

3 个答案:

答案 0 :(得分:4)

您可以更改

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

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

在第二种情况下,temp定义了if,因此temp数组在for循环中可见。

编辑:阅读关于variable scope。您可以找到更多信息here

答案 1 :(得分:0)

在"范围"中声明变量你希望它可以编辑/阅读。

如果你想让它在if语句之外可用,那么在方法的开头声明它(在if语句之外)。

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;
     }
 }

并非完全相关,但this可能有助于阅读文章。

答案 2 :(得分:0)

您必须从if语句外部定义数组。你可以遵循两种方式。

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


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

第一个必须在使用之前进行空检查。第二个给初始化编译器错误。所以你可以添加else子句并设置空数组。