我想知道是否有辦法使用 if-else 陳述句來觸發讓用戶重新輸入有效輸入的回圈?我曾嘗試使用 While 回圈,因為這種結構在技術上有效,但我無法獲得正確的實作。到目前為止,我已經使用 if-else 條件來單獨測驗有效范圍內的每個數字,如果用戶輸入任何這些值,它就會繼續。else 陳述句告訴用戶它是不正確的,但我似乎無法找到一種方法讓用戶回傳,直到他們輸入一個有效的數字。這是我正在使用的代碼:
class Humanoid < Player
def play()
userinput = print 'Enter your move [1 - 5]: '
input = gets&.rstrip
if input == '5'
return input
elsif input == '4'
return input
elsif input == '3'
return input
elsif input == '2'
return input
elsif input == '1'
return input
else
return "That is not an option, choose again"
end
end
end
如果不正確,是否可以提示用戶輸入另一個數字?我覺得應該是,但我目前不知道該怎么做。
uj5u.com熱心網友回復:
我會使用一個loop永遠運行的簡單,除非你明確地return(或break)從中:
class Humanoid < Player
def play()
loop do
print 'Enter your move [1 - 5]: '
input = gets.chomp
if %w[1 2 3 4 5].include?(input)
return input
else
puts "That is not an option, choose again"
end
end
end
end
此外,我清理了你的條件。
uj5u.com熱心網友回復:
我會這樣寫:'
loop do
userinput = print 'Enter your move [1 - 5]: '
input = gets&.rstrip
if input == '5'
return input
elsif input == '4'
return input
elsif input == '3'
return input
elsif input == '2'
return input
elsif input == '1'
return input
puts "That is not an option, choose again"
end
基本上,這只會讓它永遠重復,直到回傳一個值。如果沒有,則列印問題并再次回圈。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/473800.html
