// Ilustrates the use of two iterators that implement the an
interface called SIterator
// (there is an Iterator interface with the same funtionality in the Java
library)
public class StringIteratorProblem
{
public static void main(String[] args)
{
String movie =
"Software Engineering, it is great";
StringIterator iter1 = new StringIterator(movie);
printWithSpaces(iter1);
StringIterator2
iter2 = new StringIterator2(movie);
printWithSpaces(iter2);
}
public static void printWithSpaces(SIterator iter)
{
for (; iter.hasMoreElements(); iter.nextElement())
{
System.out.print(iter.value() + " ");
}
System.out.println();
}
}
public interface SIterator
{
public
boolean hasMoreElements();
public
Object nextElement();
public
void reset();
public
Object value();
}
class StringIterator
implements SIterator
{
String string;
int index;
StringIterator(String
s) { string = s; index = 0; }
public
boolean hasMoreElements() {
return index < string.length(); }
public
Object nextElement()
{
char temp = string.charAt(index);
index++;
return new Character(temp);
}
public
void reset() { index = 0; }
public
Object value()
{
char temp = string.charAt(index);
return new Character(temp);
}
}
class StringIterator2 implements
SIterator
{
String string;
int index;
StringIterator2(String
s) { string = s; index = 0; }
public
boolean hasMoreElements() {
return index < string.length(); }
public
Object nextElement()
{
char temp = string.charAt(index);
index = index + 2;
return new Character(temp);
}
public
void reset() { index = 0; }
public
Object value()
{
char temp = string.charAt(index);
return new Character(temp);
}
}
Output:
S o f t w a r e E n g i n e e
r i n g , i t i s g r e a t
S f w r n i e r n , i s g e t