【发布时间】:2018-04-25 21:56:26
【问题描述】:
我是新手,但在仔细查看其他问题后找不到这个问题的答案。
为什么有时需要声明变量而有时不需要?我举两个例子:
示例 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,我将不胜感激。
【问题讨论】:
-
经验法则:从最窄的块开始。并且仅在需要时将其“向上”移动。
-
因为你在 for 循环的关闭 } 之后使用它。范围到此为止,因此您必须声明该变量,以便之后可以访问它。也许您应该阅读一下有关范围的内容。
-
该变量在其作用域结束后不再存在。
-
因为您在 for 循环执行后访问
i变量。在for中定义的变量只在循环执行之前有作用域。 -
对于 j,不能保证你的循环会运行,所以如果你想在循环之后打印它,就需要设置它