Bug with query.hasNext()

Try
while (r.hasNext())…