[英]For-loop type - can't recognise it
在 Robert Sedgewick 的书中,我发现了以下代码:
public class QuickF{
public static void main(String[] args){
int N = 20;
int id[] = new int[N];
for (int i=0; i<N; i++){
id[i] = i;
}
for( In.init(); !In.empty(); ){
int p = In.getInt(), q = In.getInt();
int t = id[p];
if (t==id[q]) continue;
for (int i =0; i<N; i++){
if (id[i] == t) id[i] = id[q];
}
Out.println(" " +p+""+q);
}
}
}
我的问题是关于这一行: for( In.init(); !In.empty(); )
。 这是什么类型的 forr 循环? 这在语法上合法吗? 如果是,此 for 循环类型的文档是什么?
这是一个基本的for
循环。
它记录在Java Language Specification 的14.14.1节中。 Statement 的基础:
BasicForStatement:
for ( [ForInit] ; [Expression] ; [ForUpdate] ) Statement
ForInit:
StatementExpressionList
LocalVariableDeclaration
ForUpdate:
StatementExpressionList
StatementExpressionList:
StatementExpression {, StatementExpression}
通常,你会看到它是这样的:
ForInit: int i = 0 // LocalVariableDeclaration
Expression: i < 10
ForUpdate: i++ // StatementExpression
for ( int i = 0 ; i < 10 ; i++ ) {
// code
}
// mostly the same as:
int i = 0;
while ( i < 10 ) {
// code
i++;
}
大体相同,因为i
的范围仅限于循环,并且continue
语句将转到i++
语句,而不是直接返回循环。
但是正如您所看到的,所有 3 个都是可选的,其中ForInit
可以是语句列表而不是变量声明,并且Expression
默认为true
。
ForInit: In.init() // StatementExpression
Expression: !In.empty()
ForUpdate: // not present
for ( In.init() ; !In.empty() ; ) {
// code
}
// same as:
In.init();
while ( !In.empty() ) {
// code
}
Expression
默认为true
表示以下相同。 我个人更喜欢第一个,因为for (;;)
几乎读起来像“永远”。
for (;;) { // loop forever
// code
}
while (true) { // loop forever
// code
}
这只是一个普通的 for-loop 。
for
语句的一般形式可以表示如下:for (initialization; termination; increment) { statement(s) }
它与for (int i = 0; i < N; i++)
没有什么不同,除了不同的初始化和终止,并且没有增量。
您可以省略 increment 语句,因为
for
循环的三个表达式是可选的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.