In Robert Sedgewick's book i found the following code:
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);
}
}
}
My question is about this line: for( In.init(); !In.empty(); )
. What type of forr loop is this? Is this syntacticaly legal? If yes, what is the documentation of this for loop type?
It's a basic for
loop.
It is documented in the Java Language Specification , section 14.14.1. The basic for Statement :
BasicForStatement:
for ( [ForInit] ; [Expression] ; [ForUpdate] ) Statement
ForInit:
StatementExpressionList
LocalVariableDeclaration
ForUpdate:
StatementExpressionList
StatementExpressionList:
StatementExpression {, StatementExpression}
Normally, you'll see it like this:
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++;
}
Mostly the same, since the scope of i
is limited to the loop, and the continue
statement will go to the i++
statement, not directly back to the loop.
But as you can see, all 3 are optional, where ForInit
can be a statement list instead of a variable declaration, and Expression
defaults to 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
}
The Expression
defaulting to true
means that the following are the same. I personally prefer the first, since for (;;)
almost reads like "forever".
for (;;) { // loop forever
// code
}
while (true) { // loop forever
// code
}
It's just a regular for-loop .
The general form of the
for
statement can be expressed as follows:for (initialization; termination; increment) { statement(s) }
It is no different from for (int i = 0; i < N; i++)
, except with a different initialization and termination , and without an increment .
You are allowed to omit the increment statement because
The three expressions of the
for
loop are optional
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.