如果他們輸入的輸入不是有效的檔案名,我將如何讓我的程式繼續向用戶詢問有效的檔案名?這是我當前的代碼:
print "What is the name of the input file that contains the list of students to be grouped: "
input_file = gets.chomp
if (File.exist?(input_file))
puts "this is a valid file"
else
puts "this is not valid"
end
uj5u.com熱心網友回復:
要一直要求用戶提供輸入,直到滿足您的條件(檔案存在),您將不得不使用回圈。您可以使用多種方式,這里有一個使用 的示例until,從您提供的代碼開始。
puts "What is the name of the input file that contains the list of students to be grouped: "
input_file = gets.chomp
until File.exist?(input_file)
puts "this is not valid"
puts "What is the name of the input file that contains the list of students to be grouped: "
input_file = gets.chomp
end
puts "this is a valid file"
或其他版本以使您的代碼更加干燥
input_file = ''
until File.exist?(input_file)
puts "What is the name of the input file that contains the list of students to be grouped: "
input_file = gets.chomp
puts "this is not valid" if !File.exist?(input_file)
end
puts "this is a valid file"
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/516604.html
標籤:红宝石目录
