java - Why does an Iterator not go up when called twice? -


the following program iterates on string. iterator cuts between whitespaces , returns each word. use each loop use iterable string , within loop iterate again on same string using same iterator in outer loop. output is: hello hello hello 0 hello 2 etc...

but should be: hello 0 hello 2 ... because outer loop increased counter of iterator. think i'm missing in picture iterators work... appreciated!

the code:

import java.util.iterator;  public class toplevelclass{      public toplevelclass(final string... strings) {         for(string nextsentence : strings){             iterablesentence itsentence = new iterablesentence(nextsentence);             for(string nextword : itsentence){                 for(string nextword2 : itsentence){                     system.out.println(nextword + " " + nextword2);                 }             }         }     }      public static void main(string... args){         final toplevelclass scenedata = new toplevelclass("hello 0 2");     }      private class iterablesentence implements iterable<string>{          private final string sentence;          private iterablesentence(string sentence){             this.sentence = cleanup(sentence);         }          private iterablesentence(iterablesentence itsentence){             this.sentence = itsentence.sentence;         }          @override public iterator<string> iterator(){             return new sentenceiterator();         }          private class sentenceiterator implements iterator<string>{              private final string[] words = sentence.split(" ");             private int counter = 0;              @override public boolean hasnext(){                 return counter < words.length;             }              @override public string next(){                 //system.out.println("called");                 return words[counter++].replaceall("\\s+","");             }         }      } } 

the for loop calls iterator() on iterablesentence end 2 independent iterators.

if understand want iterators not way t go , easiest thing use nested loops.


Comments

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -