Java Reference
In-Depth Information
Now imagine you changed the conditional expression from i >0 to i <0 . In the example with the
while loop, you would first check the condition 10<0 , which evaluates to false . The loop would
be skipped and the program would continue below the while loop. In the second example with the
do while loop, it would first execute the loop with i =10 , then evaluate the condition 9<0 and find it
to be false . The do while loop would not be repeated at this point.
A do while loop is useful when you want to ensure statements in the loop are executed at least the
first time. It can be troublesome if it is possible to cause an error by executing the statements before
checking the conditional expression. Consider the following example, which was used in the for
loop section earlier:
int[] sales2014 = {500,720,515,377,400,435,510,1010,894,765,992,1125};
int[] staff2014 = {7,5,5,5,5,6,6,7,7,8,9,9};
int[] salesPerStaff = new int[12];
int totalSales2014 = 0;
for (int i=0; i<sales2014.length; i++){
salesPerStaff[i] = sales2014[i]/staff2014[i];
totalSales2014 = totalSales2014 + sales2014[i];
}
It is possible to implement this with a do while loop instead:
int[] sales2014 = {500,720,515,377,400,435,510,1010,894,765,992,1125};
int[] staff2014 = {7,5,5,5,5,6,6,7,7,8,9,9};
int[] salesPerStaff = new int[12];
int totalSales2014 = 0;
int i = -1;
do {
salesPerStaff[i] = sales2014[i]/staff2014[i];
totalSales2014 = totalSales2014 + sales2014[i];
i++;
} while (i<sales2014.length);
You must ensure that the variable i is initialized with a value that will refer to an element in the
array. In the example, i =-1 will cause an error, as would i =12 , because the arrays only have ele-
ments between 0 and 11.
a do while Loop
try it out
 To create a do while loop, follow these steps:
1.
Create a new class named DoWhileLoop , following the same process. You can continue to use the
same Chapter5 project. Create a new class by right-clicking on the src folder in your project.
Select New and then Class.
2.
In the Name field, enter the name of your class, DoWhileLoop, beginning with a capital letter
by Java convention. In the bottom portion of the New Java Class window, there is a section
that reads: “Which method stubs would you like to create?” You may choose to check the
box next to "public static void main(String[] args)" to automatically create a main
method.
Search WWH ::




Custom Search