This file that has the outline of an iterator which will be used to return each char within a String. Complete the hasNext() and next() methods to enable this iteration. In case it is of use, String has two methods which may provide useful -- size() (returning the number of chars it contains) and charAt() (returning the character at the location passed as an argument).
import java.util.Iterator; import java.util.NoSuchElementException; public class CharacterIterator implements Iterator<Character> { /** The String whose characters will be returned by this Iterator. */ private String characterSource; /** The next character in the String which will be returned by the Iterator. */ private int cursor; /** * Create a new Iterator which can be used to go through the characters in this String. * * @param str Source of characters over which we will be iterating. */ public CharacterIterator(String str) { cursor = 0; characterSource = str; } /** Returns whether the iterator has a next object. */ public boolean hasNext() { } /** Returns the next object in the iterator. */ public Character next() throws NoSuchElementException { } public void remove() { throw new UnsupportedOperationException(); } }
Here are the two methods filled for you:
import java.util.Iterator;
import java.util.NoSuchElementException;
public class CharacterIterator implements
Iterator<Character> {
/** The String whose characters will be returned by this Iterator.
*/
private String characterSource;
/** The next character in the String which will be returned by
the Iterator. */
private int cursor;
/**
* Create a new Iterator which can be used to go through the
characters in this String.
*
* @param str Source of characters over which we will be
iterating.
*/
public CharacterIterator(String str) {
cursor = 0;
characterSource = str;
}
/** Returns whether the iterator has a next object. */
public boolean hasNext() {
return cursor < characterSource.length();
}
/** Returns the next object in the iterator. */
public Character next() throws NoSuchElementException {
cursor++;
return characterSource.charAt(cursor-1);
}
public void remove() {
throw new UnsupportedOperationException();
}
}
Get Answers For Free
Most questions answered within 1 hours.