Question 5-3
Define a class NumberIterator for iterating through
a sequence of numbers.
It should support the following methods.
- NumberIterator(int start, int stop)
- (Constructor method) Constructs an object for iterating through the
integers beginning at start and going up to stop.
The constructor assumes that start is less than
stop.
- boolean hasMoreNumbers()
- Returns true if there are more numbers remaining in the
sequence.
- int nextNumber()
- Returns the current number in the sequence and steps the iterator
forward, so that the next call to this method returns the
following number in the sequence. This method initiates a
NoSuchElementException if the sequence has no more elements
remaining.
For example, if you defined this class properly, I should be able
to write the following class to test it. When executed, its
run() method would print ``5 6 7 8''.
public class NumberIteratorTest {
public static void run() {
NumberIterator it = new NumberIterator(5, 8);
IO.print(it.nextNumber());
while(it.hasMoreNumbers()) {
int i = it.nextNumber();
IO.print(" " + i);
}
}
}
Solution
public class NumberIterator {
private int current;
private int last;
public NumberIterator(int start, int stop) {
current = start;
last = stop;
}
public boolean hasMoreNumbers() {
return current <= last;
}
public int nextNumber() throws NoSuchElementException {
if(current <= last) {
current++;
return current - 1;
} else {
throw new NoSuchElementException();
}
}
}
Back to 8:00 Quiz 5