简体   繁体   English

Java遍历整数数组

[英]Java looping through integer array

Consider the following Java code: 考虑以下Java代码:

int[] array = {1, 2, 3, 4, 5, 6};
for(int i : array) {
    System.out.print(i + " ");
}

The above code obviously prints the contents of the array. 上面的代码显然打印了数组的内容。

1 2 3 4 5 1 2 3 4 5

My question is why doesn't Java allow this? 我的问题是Java为什么不允许这样做?

int[] array = {1, 2, 3, 4, 5, 6};
int i;
for(i : array) {
    System.out.print(i + " ");
}

EDIT: when I compile the 2nd program, I get the following error: 编辑:当我编译第二个程序时,出现以下错误:

Main.java:14: error: bad initializer for for-loop
        for(i : array) {
            ^
1 error

Because Java forces you to declare a variable here. 因为Java强制您在此处声明变量。 The JLS, Section 14.14.2 , defines the enhanced for loop with syntax: JLS第14.14.2节使用以下语法定义了增强的for循环:

EnhancedForStatement: EnhancedForStatement:

 for ( {VariableModifier} UnannType VariableDeclaratorId : Expression ) Statement 

EnhancedForStatementNoShortIf: EnhancedForStatementNoShortIf:

 for ( {VariableModifier} UnannType VariableDeclaratorId : Expression ) StatementNoShortIf 

The UnannType is a type for the variable being declared. UnannType是要声明的变量的类型。

It goes on to state that such an enhanced for loop is the equivalent of this, for looping over Iterable s... 它继续指出,这种增强的for循环与此等效,用于遍历Iterable s。

for (I #i = Expression.iterator(); #i.hasNext(); ) {
    {VariableModifier} TargetType Identifier =
        (TargetType) #i.next();
    Statement
}

... and for arrays... ...对于数组...

T[] #a = Expression;
L1: L2: ... Lm:
for (int #i = 0; #i < #a.length; #i++) {
    {VariableModifier} TargetType Identifier = #a[#i];
    Statement
}

It's clear that the variable is a locally declared variable inside the loop. 显然,该变量是循环内部的局部声明变量。

What is the error showing? 显示的错误是什么? Maybe you should initialize the varible: 也许您应该初始化变量:

int i = 0;

You are using “Enhanced” for-loops. 您正在使用“增强型” for循环。 This is a feature available after Java 1.5. 此功能在Java 1.5之后可用。 The syntax of enhanced for loop is for循环的语法为

for(Object obj : List) {
    ...
}

If you write in other format it will throw a compilation error. 如果您以其他格式编写,将引发编译错误。 Basically the code you wrote is syntactically incorrect. 基本上,您编写的代码在语法上是错误的。 This will be a compilation error. 这将是一个编译错误。

You can refer What is the syntax of enhanced for loop in Java? 您可以参考Java中for循环的增强语法什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM