我是一名新手,但在仔细查看其他问题后仍然找不到答案。
为什么有时需要声明变量,有时不需要呢?以下是两个例子:
示例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
?我会感激不尽您的解答。
i
变量。在for循环中定义的变量仅在循环执行期间具有作用域。 - rachit