Era meglio che nel codice precedente sostituissi

if (tentativi>0)

con

while (tentativi>0)