Looping through All StudentsThe test method testRosterReport demonstrates how to produce a report for two students. You know that the code to construct the report is written with the assumption that there will be only two students.
What you would like to be able to do is to execute the same three lines of code for each of the students in the ArrayList, regardless of how many students the ArrayList contains. There are several ways of doing this in Java. The most straightforward means in J2SE 5.0 is to use a for-each loop.[3]
There are two forms of the for-each loop. The first form, which uses opening and closing braces following the loop declaration, allows you to specify multiple statements as the body of the for-each loop.
The second form allows you to define the body as a single statement only, and thus requires no braces:
In Lesson 7, you will learn about another kind of for loop that allows you to loop a certain number of times instead of looping through every element in a collection. The Java VM executes the body of the for loop once for each student in the collection students.
A reading of the above for-each loop in English-like prose: Assign each object in the collection students to a reference of the type Student named student and execute the body of the for loop with this context. |
Thursday, October 15, 2009
Looping through All Students
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment