Java Reference
In-Depth Information
step to do inside the outer
for
loop; this “resets” the value to zero each time you change employee
by incrementing the outer
for
loop. If you initialize this variable outside of the
for
loops, like the
wage
variable, it will continue adding all the employees' hours together.
Then the inner
for
loop begins. One important difference here is the termination condition.
In the outer
for
loop, you stop when the iterator exceeds the length of the
hoursWorked
array,
that is, the number of elements or number of employees, which is 3. In the inner
for
loop, you
stop when the iterator exceeds the length of the first element of the
hoursWorked
array, that is
the number of elements in the array, which is the first element or the number of days in the week
(which is 5).
Inside the inner
for
loop, you simply add each day's hours to the total
weeklyHours
for the current
employee. After the five iterations for each day of the week, you exit the inner
for
loop.
Now, you are still inside the outer
for
loop, but have calculated the hours from the inner
for
loop.
The
weeklyHours
value is printed as well as the
wage
. Since that was a
println
command, the next
print statement will begin on a new line. The weekly pay is calculated by multiplying the hours by
the wage and this is printed on a new line. This concludes the outer loop, so the program will incre-
ment the value of
x
by 1 and return to the start of the outer loop. After three iterations, one for each
employee, this part of the program will be done. If you put all of this inside the
main
method of a
class, it is executable.
creating while loops
A
while
loop is an alternative loop structure that's based on meeting a certain condition, rather
than iterating a set number of times. The standard syntax of a
while
loop is as follows:
while (/*conditional expression*/) {
/*execute these statements*/
}
Remember the difference between a
for
loop and an enhanced
for
loop: the
for
loop iterator is ini-
tialized in the loop expression, but in an enhanced
for
loop, an array must be declared somewhere
prior to entering the
for
loop. A
while
loop is similar to the enhanced
for
loop in this way. You
will need to initialize some variable before the
while
loop that will be evaluated as part of the con-
ditional expression.
When the execution of a program reaches a
while
loop, it will first check to see if the conditional
expression evaluates to
true
. If so, it will enter the loop and execute the statements inside the loop.
When the end of loop is reached, it will return to the conditional expression and check if it still
evaluates to
true
. If so, the loop will be repeated. It should be clear, then, that evaluation of the
conditional statement should change at some point during the looping process. Otherwise, the loop
iterations will never end. Consider the following code example:
int i = 10;
while (i > 0){
System.out.println(i);
}
Search WWH ::
Custom Search