有人可以请教我以下事项:
public class Loopy {
public static void main(String[] args)
{
int[] myArray = {7, 6, 5, 4, 3, 2, 1};
int counterOne;
for (counterOne = 0; counterOne < 5; counterOne++) {
System.out.println(counterOne + " ");
}
System.out.println(counterOne + " ");
int counterTwo = 0;
for (counterTwo : myArray) {
System.out.println(counterTwo + " ");
}
}
}
在for循环中,我们在循环外声明 counterOne 并在循环内使用它 . 这是正确的,只要我们在循环完成后不使用 counterOne .
在foreach循环中,我们还在循环外声明 counterTwo 然后在循环内使用它 only . 但是,在这种情况下会抛出错误:
“线程中的异常”主“java.lang.RuntimeException:无法编译的源代码 - 找不到符号符号:class counterTwo location:class package1.Loopy”
你能帮我理解为什么吗?
两者之间的唯一区别是 counterOne 被初始化为零,然后逐步分配值(小于5) .
在foreach循环中, counterTwo 被逐个分配,每个数组项 .
如果我们在第二个for循环中进行此调整,该程序将起作用: for(int counterTwo : myArray) ,而第一个适用于两种情况:
现有的一个
for (counterOne = 0; counterOne < 5; counterOne++)