dimanche 14 juillet 2019

Using flow control to request the user inputs an integer as opposed to a string

I've created a simple program that asks a user for a number. I'm working with flow control to ensure that the user enters only a number, and if the user enters anything other than a number, the program prompts the user to "Please enter a number". Even when the user enters a number, the flow control statement asking the user to "Please enter a number" runs.

I'm not getting any error messages, but one of my if/else statements must have inappropriate syntax. I've done research about what "variable" should be set to to achieve the desired output, but I must not have the appropriate boolean value.

   puts "Enter a number."
   variable = gets.chomp
   variable = variable.to_i

   if variable != Integer
     puts "Please enter a number."
   elsif variable == Integer 
     puts "Thank you. Your number is #{variable}."
   end

Even when I actually enter a number in the terminal, I only get "Please enter a number." I expect that when I enter a number, I will get "Thank you. Your number is #{variable}."

Aucun commentaire:

Enregistrer un commentaire