java: while loop - statement with a semicolon before going into statements between curly braces?

荒凉一梦 提交于 2020-01-25 10:07:44

问题


I was looking at another page here on stackoverflow and came across a working implementation of cycle sort, but I don't understand how a statement with a semicolon can exist before the curly braces in a while loop. I thought that the while loop is supposed to completely terminate and take no further actions once it finds a statement with a semicolon, so how is it that the code within the curly braces is getting executed? At first glance, I would interpret this as "var" gets incremented with each iteration of the while loop - but I know this is not the case because removing it from that spot and putting the "var++" inside of the curly braces causes an infinite loop.

Under exactly which condition is "var" incremented? Either an explanation, or a link that explains similar syntax:

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

would be appreciated. Thank you. Below is the code taken from 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;

}


回答1:


The while loop ends with var++

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

The code after that is not part of the while loop at all.

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



回答2:


C-like languages allow you to enclose arbitrary code in braces to create a block scope, with or without other syntactic constructs.
The code in the braces is being executed as ordinary code after the loop.

If you take out the while line completely, it will still run.



来源:https://stackoverflow.com/questions/12658242/java-while-loop-statement-with-a-semicolon-before-going-into-statements-betwe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!