Java Reference
In-Depth Information
SR 5.23
Assume the
int
variable
value
has been initialized to a positive inte-
ger. Write a
while
loop that prints all of the positive divisors of each
number from one to
value
. For example, if
value
is 4, it prints
divisors of 1: 1
divisors of 2: 1 2
divisors of 3: 1 3
divisors of 4: 1 2 4
An
iterator
is an object that has methods that allow you to process
a collection of items one at a time. That is, an iterator lets you step
through each item and interact with it as needed. For example, your
goal may be to compute the dues for each member of a club or print
the distinct parts of a URL. The key is that an iterator provides a con-
sistent and simple mechanism for systematically processing a group of items. Since it
is inherently a repetitive process, it is closely related to the idea of loops.
KEY CONCEPT
An iterator is an object that helps
you process a group of related
items.
Technically an iterator object in Java is defined using the
Iterator
interface,
which is discussed in Chapter 7. For now it is simply helpful to know that such
objects exist and that they can make the processing of a collection of items easier.
Every iterator object has a method called
hasNext
that returns a
boolean
value
indicating if there is at least one more item to process. Therefore the
hasNext
method can be used as a condition of a loop to control the processing of each
item. An iterator also has a method called
next
to retrieve the next item in the
collection to process.
There are several classes in the Java standard class library that define itera-
tor objects. One of these is
Scanner
, a class we've used several times in previous
examples to help us read data from the user. The
hasNext
method of the
Scanner
class returns true if there is another input token to process. And, as we've seen
previously, it has a
next
method that returns the next input token as a string.
The
Scanner
class also has specific variations of the
hasNext
method, such as
the
hasNextInt
and
hasNextDouble
methods, which allow you to determine if the
next input token is a particular type. Likewise, as we've seen, there are variations
of the
next
method, such as
nextInt
and
nextDouble
, which retrieve values of
specific types.
When reading input interactively from the standard input stream, the
hasNext
method of the
Scanner
class will wait until there is input available, then return
true. That is, interactive input read from the keyboard is always thought to have
Search WWH ::
Custom Search