Java Reference
In-Depth Information
Similarly,
x
and
y
are often used as index names in nested
for
loops. You will often encounter the
use of nested
for
loops to iterate through a matrix of values. Here is an example of that type to
demonstrate the use of nested
for
loops.
Suppose you run a small business with three employees. You store the hours worked by each
employee in a matrix like the one shown in Table 5-3.
tableĀ 5-3:
Weekly Hours Worked by Employee
employee
monday
tuesday
Wednesday
thursday
friday
Chris
2
8
2
3
3
Danielle
4
4
4
4
4
Michael
5
0
5
5
5
By using nested
for
loops, you can iterate through all the entries of this matrix, where the position
(0,0), first row and first column, refers to the hours worked by Chris on Monday, and position (1,3),
second row and fourth column, refers to the hours Danielle worked on Thursday. One
for
loop will
refer to the column and the other will refer to the row.
int[][] hoursWorked = {{3,2,8,2,3},{4,4,4,4,4,4},{5,5,0,5,5}};
String[] employees = {"Chris", "Danielle", "Michael"};
double wage = 8.30;
for (int x = 0; x < hoursWorked.length; x++){ //outer for loop
System.out.print(employees[x] + " worked ");
int weeklyHours = 0;
for (int y = 0; y < hoursWorked[0].length; y++){ //inner for loop
weeklyHours += hoursWorked[x][y];
} //close inner for loop
System.out.println(weeklyHours + " hours at " + wage + " per hour.");
double weeklyPay = weeklyHours * wage;
System.out.println("Weekly Pay: " + weeklyPay);
} //close outer for loop
The two-dimensional
int
array
hoursWorked
represents the matrix shown in Table 5.3. Each row
is a one-dimensional
int
array with five elements. A string array
employees
stores the names of the
three employees. A
double
represents the hourly wage paid to employees. Here all employees receive
the same pay, but if they are different, there could be a
double
array set up similarly to the array for
names.
The outer loop iterates three times, one for each row in the matrix, in other words, once for each
employee. When
x
= 0
, this refers to the first row of the matrix and the first element in all the
arrays. Remember, in
hoursWorked
, the first element is itself an array. First, you print the employee's
name to the console. Note, this is a
print
command, rather than
println
, so whatever is printed
next will continue on the same line. Then you initialize
weeklyHours
to zero. This is an important
Search WWH ::
Custom Search