如何使用方法将用户输入限制为大于0的整数?

时间:2017-08-17 16:49:55

标签: ruby loops methods

每次运行此代码时,即使我在第一次尝试时输入大于0的整数,我也会收到提示“INTEGER GREATER THAN 0”。我试图用verify方法完成的是输入只接受一个大于0的整数,如果他们输入其他东西,它会提示它们“INTEGER GREATER THAN 0”。任何帮助将不胜感激。

def verify(input)
  puts "please input an integer > 0"
  input = gets.chomp
  while input == 0 || input.class != Fixnum
    puts "INTEGER GREATER THAN 0"
    input = gets.chomp!.to_i
  end
end

puts "for your first number:"
num_1 = verify(num_1)
puts "for your second number:"
num_2 = verify(num_2)

def div(num_1, num_2)
  num_1 / num_2
end
def rem(num_1,num_2)
  num_1 % num_2
end

puts "#{num_1.to_s} divided by #{num_2.to_s} is #{div(num_1, num_2)} remainder #{rem(num_1,num_2)}"

1 个答案:

答案 0 :(得分:0)

修正了两个错误。

1.Sergio Tulentsev指出你必须将输入转换为整数。

2.您需要返回验证方法的输入。

3.添加is_integer?方法

def is_integer?(param)
  true if Integer(param) rescue false
end

def verify(input)
  puts "please input an integer > 0"
  input = gets.chomp

  while input.to_i <= 0 || !is_integer?(input)
    puts "INTEGER GREATER THAN 0"
    input = gets.chomp!
  end

  return input.to_i
end

puts "for your first number:"
num_1 = verify(num_1)
puts "for your second number:"
num_2 = verify(num_2)

def div(num_1, num_2)
  num_1 / num_2
end
def rem(num_1,num_2)
  num_1 % num_2
end

puts "#{num_1.to_s} divided by #{num_2.to_s} is #{div(num_1, num_2)} remainder #{rem(num_1,num_2)}"