Vincents
Vincents

Reputation: 43

Strange printing behavior of Iterator-loop

I'm building a program at the moment for a graph that uses iterators(BFS) to check for connectivity, but for some reason the method that checks for connectivity is behaving in a strange way whenever I try to print it.

This is how the code looks at the moment:

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;

    }

And the output comes as:

A
B
C
D
B
A
C
D
C
B
D
A
D
B
C
A
The graph is connected.

The only reason it's printing the vertices is to see if the iterator is working, which it apparently is. However, as soon as I comment out System.out.println(connection.next), nothing at all prints. There's no error message, nothing. I even try to print out graph.isConnected directly in the driver, and it doesn't show me anything. Before this I tried having it print out the message in the main method depending on the value of the boolean result, but that didn't work either.

The only thing I actually want printed out is the last line, which states whether the graph is connected or not. Unfortunately, given how the method is behaving right now, it won't print anything if I comment out the test line in the middle while loop.

Am I doing something wrong here? Why is the method behaving like this?

Upvotes: 1

Views: 132

Answers (1)

fjc
fjc

Reputation: 396

If you comment out:

   System.out.println(connection.next());

You still need to do this:

   connection.next();

Otherwise connection never gets advanced.

Upvotes: 2

Related Questions