Java Reference
In-Depth Information
Enter first name or ! to end:
Judy
Enter surname:
Dench
Enter first name or ! to end:
Jennifer
Enter surname:
Aniston
Enter first name or ! to end:
!
You added 4 people to the cast:
Johnny Depp
George Clooney
Judy Dench
Jennifer Aniston
The vector currently has room for 6 more people.
How It Works
Here you be assembling an all-star cast for a new blockbuster. The main() method creates a Person vari-
able, which is used as a temporary store for an actor or actress, and a Vector<Person> object, filmCast ,
to hold the entire cast.
The while loop uses the readPerson() method to obtain the necessary information from the keyboard
and create a Person object. If ! is entered from the keyboard, readPerson() returns null , and this ends
the input process for cast members.
You output the number of stars entered with these statements:
int count = filmCast.size();
System.out.println("You added " + count +
(count == 1 ? " person": " people") + " to the
cast:");
The size() method returns the number of objects in the vector, which is precisely what you want. The
complication introduced by the conditional operator is just to make the grammar in the output sentence
correct.
Just to try it out you output the members of the cast using a ListIterator<Person> object. You could
do the job just as well with an Iterator<Person> object or even a collection-based for loop. Using an
iterator is still relatively simple:
ListIterator<Person> thisLot = filmCast.listIterator();
while(thisLot.hasNext()) { // Output all elements
System.out.println( thisLot.next());
}
Instead of an iterator, you could have used the get() method for the filmCast object to retrieve the act-
ors:
Search WWH ::




Custom Search