Problem java.lang.nullpointerexception [duplicated]

-2

I am doing the implementation of the prim algorithm
    s = q2.poll (). getVal ();

        if(visited[s]==false) { 
            mst.add(q.poll());
        }
        else {
            while(visited[s]==true) { 
                q.poll();
                s = q2.poll().getVal();
            }              

And when executing I get a null pointer exception for when I assign a value to s in the while.

    
asked by Pepe Glez Ochoa 07.10.2018 в 01:12
source

1 answer

0

Because you have

 q.poll();
 s = q2.poll().getVal();

enclosed in a "while" asking for an index of the array "visited [s]" and within the same while changing "s" for another value, it is most likely that the value given by s = q2.poll().getVal(); is not an index valid for "visited [s]" and java this trying to access a "null" value, that is, it does not exist and therefore skip the exception. One of the possible solutions is to add the condition asking for "null" in the while in this way:

while(visited[s]==true && visited[s]!=null) { q.poll(); s = q2.poll().getVal(); }

I hope it will be useful for you. Good luck. Greetings.

    
answered by 07.10.2018 в 06:19