1.反向循環

Java 有另一種while循環——do-while循環。它與普通while循環非常相似,也只包含兩部分:“條件”和“循環體”。只要條件是,循環體就會一遍又一遍地執行true。一般來說,do-while循環看起來像這樣:

do
   statement;
while (condition);

或者

do
{
   block of statements
}
while (condition);

對於一個while循環來說,執行的順序是:條件循環體條件循環體條件循環體,...

但是對於一個do-while循環,它略有不同:循環體條件循環體條件循環體,......

事實上,while循環和do-while循環之間的唯一區別是循環體至少執行一次循環do-while


2.使用do-while循環的好處

do-while基本上,循環和循環之間的唯一區別while是循環do-while至少執行一次。

通常,do-while如果循環體尚未執行,則在檢查循環條件沒有意義時使用循環。例如,如果在循環體中執行某些計算,然後在條件中使用。

例子:

程序從鍵盤讀取行,直到exit輸入單詞

儘管 做的時候
String s;
while (true)
{
   s = console.nextLine();
   if (s.equals("exit"))
      break;
}
String s;
do
{
   s = console.nextLine();
}
while (!s.equals("exit"));

循環中的 and 語句的工作break方式與循環中的相同。continuedo-whilewhile


3. 比較do-while循環:Java 與 Pascal

再一次,Pascal 有一個do-while循環的模擬,但它被稱為repeat-until循環。此外,它與循環略有不同do-while。在repeat-until循環中,條件指示何時退出循環而不是何時繼續循環。

例子:

帕斯卡 爪哇
Repeat
   ReadLn(s);
Until s = 'exit';
String s;
do {
   s = console.nextLine();
}
while ( !s.equals("exit") );

與 Java 相比,Pascal 表示這一點的方式非常漂亮。我們必須從 Pascal 的例子開始,否則你會笑的。


2
任務
Java Syntax,  等級 6課堂 5
上鎖
Cat's finalize method
It's difficult to accidentally lose an object: as long as you have even one reference to an object, it remains alive. But if not, then the object is approached by the finalize method, an unpredictable assassin that works for the Java machine. Let's create this method ourselves: protected void finalize() throws Throwable. The last two words will become clear a little later.