我正在为使用迭代器(BFS)检查连接性的图形构建程序,但由于某种原因,检查连接性的方法每次都以奇怪的方式运行我尝试打印它。迭代器循环的奇怪打印行为
这是怎样的代码看起来在此刻:
public boolean isConnected() {
for(int i=0;i<numVertices;i++) {
Iterator<T> connection = iteratorBFS(i);
int count = 0;
while(connection.hasNext()) {
count++;
System.out.println(connection.next());
}
if(count!=numVertices) {
System.out.println("The graph is disjoint.");
return false;
}
}
System.out.println("The graph is connected.");
return true;
}
和输出当属:
A
B
C
D
B
A
C
D
C
B
D
A
D
B
C
A
The graph is connected.
它的打印顶点的唯一原因是,看看迭代器是否正常工作,它显然是。但是,只要我注释掉System.out.println(connection.next),什么都不打印。没有错误信息,什么都没有。我甚至尝试直接在驱动程序中打印出graph.isConnected,但它没有显示任何内容。在此之前,我试图根据布尔结果的值在主要方法中打印出消息,但那也不起作用。
我真正想要打印的唯一东西是最后一行,它说明图形是否连接。不幸的是,考虑到该方法现在的行为,如果我在while while循环中注释掉测试行,它将不会打印任何内容。
我在这里做错了什么?为什么该方法的行为如此?
您必须调用.next才能使用迭代器。删除system.out并保留connection.next() –