我试图让用户输入一个正整数(> = 1)。如果用户输入一个负整数或0,程序将注意到并说您没有输入有效的整数,请重试。到目前为止,我的程序一直有效,直到尝试输入字符串为止。输入字符串后程序中断。有人知道如何解决这个问题吗?
我尝试了elsif!barsofsoap.match(/\A[-+]?[0-9]*.?[0-9]+\Z/) 输入“您未输入整数,请输入正整数”,但这没用
loop do
puts "How many soaps are you looking to purchase? (Please put an integer)"
x = gets.chomp
barsofsoap = Integer(x) rescue false
if barsofsoap >= 1
break
else
puts "You didn't put an integer, please put an integer and try again."
end
end
我希望如果用户输入字符串,程序也不会中断。
答案 0 :(得分:5)
您可以尝试以下操作:num.positive?
请参阅此处:https://ruby-doc.org/core-2.6/Numeric.html#method-i-positive-3F
此外,您可以尝试将文本转换为整数并通过执行以下操作进行验证:
num.is_a?(Integer)
https://ruby-doc.org/core-2.6/Object.html#method-i-is_a-3F
由于输入始终是文本,因此甚至更好,您可以使用正则表达式来确保仅输入数字:"12345" =~ /\A\d+\Z/
尝试一下:
loop do
puts "How many soaps are you looking to purchase? (Please put an integer)"
barsofsoap = gets.chomp
if barsofsoap.match(/^[\d]+$/).nil?
puts "You didn't put an integer, please put an integer and try again."
elsif barsofsoap.to_i.positive?
break
else
puts "You didn't put an integer, please put an integer and try again."
end
end
答案 1 :(得分:5)
如果您使用false
作为救援值,则当前代码失败的原因。您无法比较false >= 1
。紧贴原始代码,您可以将比较结果包装到begin
/ end
块中。
loop do
puts "How many soaps are you looking to purchase? (Please put an integer)"
x = gets.chomp
begin
barsofsoap = Integer(x)
if barsofsoap >= 1
break
end
rescue ArgumentError => _error
puts "You didn't put an integer, please put an integer and try again."
end
end
或简化代码:
loop do
puts "How many soaps are you looking to purchase? (Please put an integer)"
break if (barsofsoap = gets.to_i).positive?
puts "Invalid input. Provide a positive integer."
end
上面的代码无法检测输入是字符串还是整数。通过将Integer(x)
替换为x.to_i
,如果无效,它将简单地返回0
。由于您希望用户提供一个正整数,因此它仍然要求他们提供一个新的整数。
nil.to_i #=> 0
''.to_i #=> 0
'asdf'.to_i #=> 0
'12.34'.to_i #=> 12
类似于字符串'12.34'
上方所示,将产生值12
。根据您的要求,您可能不想使用该值,而是将其标记为无效输入。在这种情况下,您可以使用正则表达式检查提供的输入。
loop do
puts "How many soaps are you looking to purchase? (Please put an integer)"
input = gets
break barsofsoap = input.to_i if input.match?(/\A[1-9]\d*\Z/)
puts "Invalid input. Provide a positive integer."
end
正则表达式/\A[1-9]\d*\Z/
将与以下内容匹配:
\A
匹配字符串的开头。[1-9]
匹配数字1-9
之一。\d*
匹配零个或多个数字0-9
。\Z
匹配字符串的结尾。如果字符串以换行符结尾,则它与换行符匹配。答案 2 :(得分:1)
其他选项,使用n.to_i.to_s == n
检查输入是否为Integer并将循环移至方法中:
def get_input_integer
loop do
puts "Enter a positive Integer"
n = gets.chomp
if n.to_i.to_s == n
return n.to_i if n.to_i.positive?
puts "It's not positive"
else
puts "It's not an integer"
end
end
end
x = get_input_integer