i need bugfixing help binding doors between rooms(4.11.1)

i am trying to make an algorythem that binds the doors of rooms between each other
rooms have a random amount of doors up to 4
the amount of doors is always even
min door amount is rooms2-2 and max room amount is 4rooms-root(rooms)*4

the main problem is that there are constantly infinit loops either from null pointer exceptions or from infinit recursive function calls

pictures: http://imgur.com/a/38SNM