import java.io.*;
import javax.swing.JOptionPane;
import java.util.*;
public class lesson {
static void printAll(ArrayList<String> names, int len)
{
Iterator it = names.iterator();
while( it.hasNext() )
{
if( ((String)it.next()).length() == len)
System.out.println( it.next() );
}
}
public static void main(String[] args) throws IOException {
ArrayList<String> names = new ArrayList<String>();
names.add("Jan");
names.add("Ivan");
names.add("Tom");
names.add("George");
printAll(names,3);
}
}
why is the output Ivan, George, shouldn’t it print only names with length 3 (which are Jan and Tom)?
it.next()advances iterator to one element. You are doingit.next()twice.if( ((String)it.next()).length() == len)advances one time and now iterator points to next()Change it to something like below: