在用户未输入else
或1
的{{1}}处,脚本应在显示错误消息后重新开始。我怎么能这样做?
2
答案 0 :(得分:4)
您需要包装整个事件in a while
loop并将变量input
初始化为类似nil
的值。
while
循环的条件应该检查值是1还是2,并且可能需要转换为.to_i
的整数,因为gets
将返回一个字符串。< / p>
# initialize to nil
input = nil
# Check if the current value (integer) is 1 or 2
while !([1,2].include?(input))
puts "Do you want to calculate celcius to fahrenheit (1) or fahrenheit to celcius(2)"
# Convert the string to an int after getting it as input
input = gets.to_i
if input == 1
puts "Please enter degrees in Celcius."
celcius = gets
fahrenheit = (celcius.to_i * 9 / 5) + 32
print "The result is "
print fahrenheit
puts "."
# elsif here, not elseif!!
elsif input == 2
puts "Please enter degrees in Fahrenheit."
fahrenheit = gets
celcius = (fahrenheit.to_i / 9 * 5) - 32
print "The result is:"
print celcius
puts "."
else
puts "Please enter option 1 or 2"
end
end
事实上,在测试负面条件时,使用while
循环(Ruby与许多其他语言不同)而不是until
循环更具可读性:
until [1,2].include?(input)
...
end
[1,2].include?(input)
是一种更为流畅的写作方式
if input == 1 || input == 2
...可以轻松扩展数组中的其他值。
答案 1 :(得分:0)
这是使用功能。
puts "Do you want to calculate celcius to fahrenheit (1) or fahrenheit to celcius(2)"
def convert
input = gets
if input == 1
puts "Please enter degrees in Celcius."
celcius = gets
fahrenheit = (celcius.to_i * 9 / 5) + 32
print "The result is "
print fahrenheit
puts "."
elseif input == 2
puts "Please enter degrees in Fahrenheit."
fahrenheit = gets
celcius = (fahrenheit.to_i / 9 * 5) - 32
print "The result is:"
print celcius
puts "."
else
puts "Please enter option 1 or 2"
convert()
end
end
如果输入!=(2 || 1)也可以。