How Do I Stabilize the Number of Loops in Java?
- 1). Initialize a variable for use within the while loop. For example, the code snippet "int count = 0;" initializes a variable named count of type integer with an initial value of zero.
- 2). Implement a while loop including an evaluation expression. The while loop will evaluate the expression and determine whether it is true. The expression must return a boolean value, true or false. The following example code snippet implements a while loop and includes a boolean expression:
while (count < 10) {
} - 3). Include a block of statements to be executed by the while loop when the evaluation expression is true. The following example code snippet includes an entire while statement with initialized variable and command statements:
int count = 0;
while (count < 10) {
System.out.println("The count is: " + count);
count++
}
This while loop prints the included text and current value of the count variable, and then it increases the value of the count variable by one each time the while loop executes. The while loop will terminate when the value of count reaches 10. - 1). Initialize a variable for use within the do-while loop. For example, the code snippet "int count = 0;" initializes a variable named count of type integer with an initial value of zero.
- 2). Implement a do-while loop including an evaluation expression. The do-while loop will evaluate the expression and determine whether it is true after the command statements within the "do-brackets" are executed the first time. The expression must return a boolean value, true or false. The following example code snippet implements a do-while loop and includes a boolean expression:
do {
"Your command statements."
} while (count < 10) {
} - 3). Include a block of statements to be executed by the do-while loop before the evaluation expression is read and when the expression is true. The following example code snippet includes an entire do-while statement with initialized variable and command statements:
int count = 0;
do {
System.out.println("The count is: " + count);
count++
} while (count < 10)
}
This do-while loop prints the included text and current value of the count variable before the evaluation expression is read, then increases the value of the count variable by one each time the do-while loop executes. The do-while loop will terminate when the value of count reaches 10. The only difference between a while and do=while loop is that a do-while loop does not evaluate the boolean expression until the bottom of the loop, forcing the loop to execute the command statements at least once.