有人可以启发我解决以下问题:
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
循环外部声明,然后仅在循环内部使用它。但是,在这种情况下会引发错误:
“线程“主”中的异常” java.lang.RuntimeException:无法编译的源代码-找不到符号symbol:类counterTwo位置:class package1.Loopy”
你能帮我理解为什么吗?
两者之间的唯一区别是,counterOne
初始化为零,然后递增地分配值(小于5)。
在foreach循环中counterTwo
,每个数组项都被分配一个。
如果我们在第二个for循环中进行此调整,则该程序将起作用:for(int counterTwo : myArray)
而在两种情况下,第一个for都将起作用:
for (counterOne = 0; counterOne < 5; counterOne++)
for语句的增强形式为:
EnhancedForStatement:
for ( {VariableModifier} UnannType VariableDeclaratorId : Expression ) Statement
EnhancedForStatementNoShortIf:
for ( {VariableModifier} UnannType VariableDeclaratorId : Expression ) StatementNoShortIf
请注意,循环中UnannType
必须存在类型声明for
。因此,您应按以下方式编写循环:
for (int z : x) {
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句