加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 03:16:10 所属栏目:Java 来源:网络整理
导读:有人可以请赐教我以下事项: 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
有人可以请赐教我以下事项:
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) {

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读