[英]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.