以下程序遍历String。迭代器在空格之间切换它并返回每个单词。我为每个循环使用a来使用可迭代字符串,并且在该循环中,我使用与外部循环中相同的迭代器在同一字符串上再次迭代。输出是: 你好你好 你好0 你好2 等...
但它应该是: 你好0 你好2 ... 因为外部循环已经增加了迭代器的计数器。所以我想我在这张图片中遗漏了一些关于迭代器工作的东西...... 任何帮助表示赞赏!
代码:
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+","");
}
}
}
}
答案 0 :(得分:0)
for
循环在iterator()
上调用IterableSentence
,因此最终会得到两个独立的迭代器。
如果我理解你真正想要做的事情,那么迭代器就不是那样了,最容易做的就是使用嵌套循环。