2015-09-28 52 views
-1

有人可以讓我知道一些資源在線,定義爲這種奇怪的實時行爲?do-while在底部聲明

int i = 0; 
do while (++i < 1) { //this compile (?!?) 
     System.out.print("i is " + i); 
} 

do while (++i < 1) // this compile also 
     System.out.print("i is " + i); 
do while (i > 1) {} 

while (i > 1) {} //this doesn't compile, the comp. wants the semicolon 

對不起,我錯過了do-while語句的內容?

在此沒有提及在所有Oracle官方鏈接: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html

編輯: 對不起,我解釋的嵌套,而作爲另一個語句。

這是困惑我原來的語句:

int i = 1; 
do while (i < 1) 
System.out.print("i is " + i); 
while (i > 1); 

這編譯...,等同於:

do { 
    while (++i < 1) // this compile also! 
    System.out.print("i is " + i); 
} 
while (i > 1); 
+3

我懷疑',而(I> 1){}'doesn't如果'i'存在編譯... – SomeJavaGuy

+1

其實'while(i> 1){}'是唯一可以編譯的循環。 – stevecross

+0

你發佈的內容不能編譯,你在'while(...)之後丟失了一個分號;'我建議你閱讀JLS:https://docs.oracle.com/javase/specs/jls/se8/ html/jls-14.html#jls-14.13 – Tunaki

回答

1

在您發佈的神諭鏈接是所有解釋:

The Java programming language also provides a do-while statement, which can be expressed as follows: 

do { 
    statement(s) 
} while (expression); 

如果我將您的代碼複製到我的IDE(Eclipse)上,這裏是我的結果:

int i = 0; 
do while (++i < 1) { //DO NOT COMPILE,Syntax error, insert "while (Expression) ;" to complete DoStatement 
     System.out.print("i is " + i); 
} 

do while (++i < 1) // DO NOT COMPILE,Syntax error, insert "while (Expression) ;" to complete DoStatement 
     System.out.print("i is " + i); 

while (i > 1) {} //COMPILE 
do while (i > 1) {} //DO NOT COMPILE,Syntax error, insert "while (Expression) ;" to complete DoStatement 
0

我不確定你在問什麼。

while(i>1){}//this doesn't compile. 

這是正確的語法。

也爲代碼DO-而行正確的說法是

do { 
    //code goes here 
} while (i > 1); 

我想我應該指出的是,一個做而行代碼會做的括號內的代碼不管,然後檢查是否需要重複。然而,while語句將檢查它是否i> 1,如果爲true,它將運行代碼。

希望這會有所幫助。

0

雖然語法不正確。 在簡單的方法,你應該這樣想這個 - >做一些事情,直到(條件) 所以這裏是語法

do{ 
//statement 
}while(condition is true);