Help here with a Ruby exercise

Asked

Viewed 40 times

0

Why even if I type 0 or 2 it doesn’t come out of second while

while opt==2
print "Digite o valor a ser depositado: "
deposito = gets.chomp.to_f
saldo = saldo + deposito
print "Pressione 0 para voltar ao menu anterior ou 2 para novo deposito: "
opt = gets.chomp.to_i
    while opt!=0 or opt!=2
       print "Opção inválida, pressione 0 para voltar ao menu anterior ou 2 
       para novo deposito: "
       opt = gets.chomp.to_i   
     end

end

  • 1

    If you type 2, it will be non-zero and will be in the loop; if you type 0, it will be different from two and will be in the loop. The only possibility that would satisfy its condition is if the number is equal to 0 and equal to 2 at the same time, which is impossible in the domain of integers. So review your condition and run table tests to validate it.

1 answer

1


I believe you’re not getting out of the 2nd while by the double condition: while opt!=0 or opt!=2

See a problem similar to yours in English: Multiple conditions in a "While" Ruby loop

One simple way to solve it is by using the decision-making structure, within the while repetition structure:

while true
   print "Opção inválida, pressione 0 para voltar ao menu anterior ou 2 
   para novo deposito: "
   opt = gets.chomp.to_i   
   if opt!=0 or opt!=2
    break
    end
end

However, I recommend reading the question, in English, to improve your code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.