Java Reference
In-Depth Information
8. Finally, add a print statement to indicate the end of the program. Use the following statement:
System.out.println("End of program");
This time, make sure it is placed after the closing bracket (}) of the while loop, but before the
closing bracket (}) of the main method. This ensures that it will not be repeated on each itera-
tion, but it will be executed once before the main method concludes.
9. Your class body should now look like this:
public class DoWhileLoop {
public static void main(String[] args) {
int i = 1;
do {
int doubled = i * 2;
System.out.println(i + " times two equals " + doubled);
i++;
} while (i <= 10)
System.out.println("End of program");
}
}
10. Save the class by clicking the disk icon or selecting File, then Save.
11. Run the application by clicking the green play icon or selecting Run, and then Run.
How It Works
Now take a look at how it works.
1. The application begins by executing the main method, which in this case is the only method.
2. The first statement initializes an integer named i with the value of 1.
3. The next statement opens a do while loop and enters the loop.
4. In the first statement inside the loop, a second int , named doubled , is assigned the value of i *2 . In
this first iteration, i =1 , so doubled =2 .
5. In the next statement of the loop, there is a println command. A line is output to the console
which reads: 1 times two equals 2 . Because the command is println instead of print , you can
imagine pressing Enter or Return at the end of the string to create a new line.
6. The last statement inside the do while loop reassigns the value of i to i +1 or i =2 .
7. When the program reaches the end of the loop, it will evaluate the conditional expression to see if
it will return to the start of the loop again. Since 2 is still less than 10, it will loop again.
8. The variable doubled is 2*2 or 4 in this iteration of the loop.
9. Another line will be output to the console, this time reading: 2 times two equals 4 .
10. The integer i will be reassigned the value of i +1 or i =3 .
11. This will continue until i =11 , and then the conditional expression will evaluate to false and it will
not return to the start of the loop. Instead, the program will continue below the loop.
Search WWH ::




Custom Search