在Java中声明变量外部Foreach循环
|
有人可以请赐教我以下事项: 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,然后仅在循环内部使用它.但是,在这种情况下会抛出错误:
你能帮我理解为什么吗? 两者之间的唯一区别是,counterOne初始化为零,然后逐步指定值(小于5). 在foreach循环中,counterTwo被逐个分配,每个数组项. 如果我们在第二个for循环中进行调整,该程序可以工作:for(int counterTwo:myArray),而第一个适用于两种情况: >现有的 解决方法从 this section of the Java Language Specification开始关于增强的for循环:
请注意,类型声明UnannType必须存在于for循环中.因此,您应该按如下方式编写循环: for (int z : x) { (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
