8:00 Quiz 5
One-page version suitable for
printing.
Statistics:
(including 5-point curve)
mean 22.317 (915.000/41)
stddev 5.425
median 22.000
midrange 19.000-25.000
# avg
1 6.66 / 10
2 4.83 / 10
3 5.83 / 10
+ 5-point curve
Question 5-1
Select which of the following best describes the purpose of each of the
circled pieces of the code.
(Note that some choices may not appear at all, and others may occur
multiple times.)
A. local variable declaration
B. class variable declaration
C. instance variable declaration
D. constructor method definition
E. class method definition
F. instance method definition
Solution
Question 5-2
Complete the method body so that it removes all strings
in list beginning with the letter initial.
It should assume that list contains only String
objects.
public static void removeAll(ArrayList list, char initial) {
}
Recall the following instance methods defined for the
ArrayList class.
- Object get(int index)
- Returns the object at index index of the list.
- Object remove(int index)
- Removes the object at index index of the list, shifting objects
at that index and beyond to fill the gap. Returns the removed object.
- int size()
- Returns the number of elements in the list.
Also recall the following instance method defined for the
String class.
- char charAt(int pos)
- Returns the character at index pos of the string.
Solution
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