Java while Loops Java's  while  are similar to the  for  loops. Java  while  enables your programs to repeat a set of operations whi...

Java while Loops

09:31 PASSOVE INCOME 0 Comments

Java while Loops

Java's while are similar to the for loops. Java while enables your programs to repeat a set of operations while a certain conditions is true.
Here is a simple example:
int counter = 0;

while(counter < 10) {

    System.out.println("counter: " + counter);

    counter++;
}
This example shows a while loop that executes the body of the loop as long as the counter variable is less than 10. Inside the loop body the counter is incremented. Eventually the counter variable will no longer be less than 10, and the while loop will stop executing.
Here is another example that uses a boolean to make the comparison:
boolean shouldContinue = true;

while(shouldContinue == true) {

    System.out.println("running");

    double random = Math.random() * 10D;

    if(random > 5) {
        shouldContinue = true;
    } else {
        shouldContinue = false;
    }

}
This example tests the boolean variable shouldContinue to check if the while loop should be executed or not. If the shouldContinue variable has the value true, the while loop body is executed one more time. If the shouldContinue variable has the value false, the while loop stops, and execution continues at the next statement after the while loop.
Inside the loop body a random number between 0 and 10 is generated. If the random number is larger than 5, then the shouldContinue variable will be set to true. If the random number is 5 or less, theshouldContinue variable will be set to false.
Like with for loops, the curly braces are optional around the loop body. If you omit the curly braces then the loop body will consist of only the first following Java statement. Here is an example:
while(iterator.hasNext())
  System.out.println("next: " + iterator.next()); // executed in loop
  System.out.println("second line");              // executed outside loop
In this example, only the first System.out.println() statement is executed inside the while loop. The second System.out.println() statement is not executed until after the while loop is finished.
Forgetting the curly braces around the while loop body is a common mistake. Therefore it can be a good habit to just always put them around the while loop body.

0 comments: