2012-09-30 56 views
0

我在看stackoverflow上的另一個頁面,並遇到了循環排序的工作實現,但我不明白帶有分號的語句如何在while循環中的花括號之前存在。我認爲while循環應該完全終止,並且一旦找到帶有分號的語句就不會採取進一步的行動,那麼大括號內的代碼是如何執行的呢?乍一看,我會將此解釋爲「var」會隨着while循環的每次迭代而遞增 - 但我知道情況並非如此,因爲將它從該位置移除並將「var ++」放入花括號內導致無限大循環。java:while循環 - 在進入大括號之間的語句之前用分號表示語句?

下到底哪個條件爲「VAR」會增加嗎?要麼解釋,或解釋類似的語法鏈接:

while (checkSomeBool) var++; 
{ 
    //other stuff happening in here 
} 

將不勝感激。謝謝。下面是CycleSort

public static final <T extends Comparable<T>> int cycleSort(final T[] array) { 
int writes = 0; 

// Loop through the array to find cycles to rotate. 
for (int cycleStart = 0; cycleStart < array.length - 1; cycleStart++) { 
    T item = array[cycleStart]; 

    // Find where to put the item. 
    int pos = cycleStart; 
    for (int i = cycleStart + 1; i < array.length; i++) 
    if (array[i].compareTo(item) < 0) pos++; 

    // If the item is already there, this is not a cycle. 
    if (pos == cycleStart) continue; 

    // Otherwise, put the item there or right after any duplicates. 
    <while (item.equals(array[pos])) pos++; 
    { 
    final T temp = array[pos]; 
    array[pos] = item; 
    item = temp; 
    } 
    writes++; 

    // Rotate the rest of the cycle. 
    while (pos != cycleStart) { 
    // Find where to put the item. 
    pos = cycleStart; 
    for (int i = cycleStart + 1; i < array.length; i++) 
     if (array[i].compareTo(item) < 0) pos++; 

    // Put the item there or right after any duplicates. 
    while (item.equals(array[pos])) pos++; 
    { 
     final T temp = array[pos]; 
     array[pos] = item; 
     item = temp; 
    } 
    writes++; 
    } 
} 
return writes; 

}

+0

它可能有助於像這樣讀取:'while(checkSomeBool){var ++; } {//其他的東西}' –

+1

這肯定是扭曲的代碼(雖然遠不及screwiest我見過)。 –

+1

我同意熱舔。我認爲提交人試圖誤導人。 –

回答

4

while環與var++

while (checkSomeBool) var++; // while ends here 

結束代碼後不屬於while迴路的一部分的。

{ 
    //other stuff happening in here - not part of the while loop 
} 
+0

+1。所以'checkSomeBool'最好涉及'var'(就像它在OP代碼中那樣),否則循環將永不執行或無休止地執行。 – Thilo

+0

是的,可能是這樣。除非有另一個線程修改條件中布爾值的值,仍然沒有等待,這可能會導致一些cpu-lock。 – techfoobar

+0

我對OP中括號內的條件過於模糊。是的,那個布爾條件確實應該在某處有'var'。我正在使用的實際代碼是:'while(item.equals(array [pos]))pos ++;' – Krondorian

3

類似C語言允許你在大括號中的任意代碼來創建一個塊範圍,有或沒有其他的語法結構所採取的代碼。
大括號中的代碼正在循環後作爲普通代碼執行。

如果完全取出while線,它仍將運行。

+0

我沒有意識到,大括號也符合這個目的。謝謝。 – Krondorian