在Java中声明变量外部Foreach循环

前端之家收集整理的这篇文章主要介绍了在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,然后仅在循环内部使用它.但是,在这种情况下会抛出错误

“Exception in thread “main” java.lang.RuntimeException: Uncompilable
source code – cannot find symbol symbol: class counterTwo location: class
package1.Loopy”

你能帮我理解为什么吗?

两者之间的唯一区别是,counterOne初始化为零,然后逐步指定值(小于5).

在foreach循环中,counterTwo被逐个分配,每个数组项.

如果我们在第二个for循环中进行调整,该程序可以工作:for(int counterTwo:myArray),而第一个适用于两种情况:

>现有的
> for(counterOne = 0; counterOne< 5; counterOne)

解决方法

this section of the Java Language Specification开始关于增强的for循环:

The enhanced for statement has the form:

EnhancedForStatement:

for ( {VariableModifier} UnannType VariableDeclaratorId : Expression ) Statement

EnhancedForStatementNoShortIf:

for ( {VariableModifier} UnannType VariableDeclaratorId : Expression ) StatementNoShortIf

请注意,类型声明UnannType必须存在于for循环中.因此,您应该按如下方式编写循环:

for (int z : x) {
原文链接:https://www.f2er.com/java/127786.html

猜你在找的Java相关文章