Looping through All Students


The 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.

You need to produce code that supports an unlimited number of students. To do this, you will modify your test to enroll additional students. Subsequently, you will recognize that the production class contains duplicate codeand the amount of duplication will only get worsesince the same three lines of code are repeated for each student, with the only variance being the index of the student.


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]

[3] Also known as an enhanced for loop.

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.

    for (Student student: students) {       // ... statements here ...    } 

The second form allows you to define the body as a single statement only, and thus requires no braces:

    for (Student student: students)       // ... single statements here; 

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.

 String getRosterReport() {    StringBuilder buffer = new StringBuilder();    buffer.append(ROSTER_REPORT_HEADER);    for (Student student: students) {       buffer.append(student.getName());       buffer.append(NEWLINE);    }    buffer.append(ROSTER_REPORT_FOOTER + students.size() + NEWLINE);    return buffer.toString(); } 

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.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net