我是新手,但在仔细研究其他问题之后找不到这个问题的答案。
为什么有时需要声明变量,有时不需要?我举两个例子:
示例1:在这里,我们不必在for循环之前声明i
。
class ForDemo {
public static void main(String[] args){
for(int i=1; i<11; i++){
System.out.println("Count is: " + i);
}
}
示例2:我们需要在循环之前声明i
。
class BreakWithLabelDemo {
public static void main(String[] args) {
int[][] arrayOfInts = {
{ 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;
int i;
int j = 0;
boolean foundIt = false;
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length;
j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
if (foundIt) {
System.out.println("Found " + searchfor + " at " + i + ", " + j);
} else {
System.out.println(searchfor + " not in the array");
}
}
如果您还可以告诉我为什么还要在for循环中指定值0来初始化变量j = 0
,我将不胜感激。
答案 0 :(得分:2)
如果在循环中声明循环变量,则只能在循环内访问它。
由于在您的上一个代码段中,您在循环结束后(i
)访问j
和System.out.println("Found " + searchfor + " at " + i + ", " + j);
,因此您必须在循环之前声明它们。
这也是你必须在循环之前初始化j
的原因。循环可能永远不会被执行(如果arrayOfInts.length
为0),但您仍然可以在提到的j
语句中访问println
,因此必须在此时对其进行初始化。
答案 1 :(得分:2)
在示例1中,i仅在for循环中使用。这就是为什么你不需要事先声明它。在例2中,i在循环中使用,但之后也在“if(foundIt)” - Block中使用。因此,它必须在循环外声明。