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
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
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) { }
Define a class NumberIterator for iterating through a sequence of numbers. It should support the following methods.
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); } } }
a. C. instance variable
b. C. instance variable
c. D. constructor method
d. F. instance method
e. A. local variable
f. F. instance method
This is slightly tricky in that you can't just go through the list removing each element beginning with the letter: Say two adjacent elements begin with the letter. When we remove the first one, the second element shifts into the slot from which we just removed. The program needs some way of checking that element again.
My technique for handling this is to go through the list backwards. It's also possible to address the problem by using a while loop within the for loop (so you repeatedly check whether the current element begins with the letter) or by decrementing the counter when an item is removed (so that the next iteration revisits that position after re-incrementing the counter to its previous position).
public static void removeAll(ArrayList list, char initial) { for(int i = list.size() - 1; i >= 0; i--) { String elt = (String) list.get(i); if(elt.charAt(0) == initial) { list.remove(i); } } }
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(); } } }