如何循环并询问用户输入

时间:2017-05-15 18:09:43

标签: ruby loops if-statement while-loop

我需要循环帮助。

我正在尝试捕获用户的输入并确定酒店计划度假的费用。

我在循环输入时遇到问题,因此如果用户没有选择任何击键(“A”,“a”,“B”,“b”,“C”,用户可以选择另一家酒店并结束程序“,”“c”,“D”或“d”),然后计算酒店的总费用。

到目前为止,我想出了这个:

puts choice = gets.chomp.downcase
puts "For how many nights?"
num=gets.chomp.to_i
puts "Okay...any other hotels?"  
puts choice = gets.chomp.downcase

#Hotel Prices  

#Hotel A
if (choice== "a" or choice=="A") 
cost_2= (num/3)*500 + (num%3)*200
end

#Hotel B
if (choice=="b" or choice=="B")
cost_3= num*250
end

#Hotel C
if (choice=="c" or choice=="C")
cost_4 = (num/3)*700 + (num%3)*300
end

#Hotel D
 if (choice== "d" or choice=="D")
  cost_5= num*500
   end

Hotel Program

3 个答案:

答案 0 :(得分:2)

您的代码有几种可能的改进,但我会尽可能简单直接地回答这个问题。

使用loop和单个if ... else if ... else ... end块代码,而不是几个单独的if语句:

loop do
  if (choice== "a" or choice=="A") 
    cost_2= (num/3)*500 + (num%3)*200
  #Hotel B
  elsif (choice=="b" or choice=="B")
    cost_3= num*250
  #Hotel C
  elsif (choice=="c" or choice=="C")
    cost_4 = (num/3)*700 + (num%3)*300
  #Hotel D
  elsif (choice== "d" or choice=="D")
    cost_5= num*500
  else
    puts "Final cost is: [...]"
    break
  end
end

您还可以考虑通过说"Type 'done' when you have finished"之类的内容来实现更明确的退出 - 并且“忽略”任何其他不是/ b / c / d / done的输入。换句话说,有些东西:

# ...
elsif (choice== "d" or choice=="D")
  cost_5= num*500
elsif choice == 'done'
  puts "Final cost is: [...]"
  break
else
  puts 'Unknown option'
end
# ...

答案 1 :(得分:2)

将代码包裹在while循环中,

continue = true
while continue
  ...
  if choice == "done"
    continue = false
  end
end

显然,最终案例可以是任何事情,而不只是"已完成"。

为了完成,这个问题的优雅解决方案将是:

loop do
  puts choice = gets.chomp.downcase
  puts "For how many nights?"
  num=gets.chomp.to_i
  puts "Okay...any other hotels?"  
  puts choice = gets.chomp.downcase

  selections = {
     a: (num/3)*500 + (num%3)*200,
     b: num*250,
     c: (num/3)*700 + (num%3)*300,
     d: (num*500)
  }

  if selections[choice.to_sym]
    cost += selections[choice.to_sym]
  else
    break
  end
end

答案 2 :(得分:-1)

这是未经测试的,但这是我使用的基本想法:

loop do

  cost = nil
  loop do

    puts 'Which hotel? (A, B, C, D)'
    hotel = gets.chomp.downcase

    puts 'For how many nights?'
    days = gets.to_i

    cost = if hotel == 'a' 
             (days / 3) * 500 + (days % 3) * 200
           elsif hotel == 'b'
             days * 250
           elsif hotel == 'c'
             (days / 3) * 700 + (days % 3) * 300
           elsif hotel == 'd'
             days * 500
           else
             puts 'Unknown hotel.'
           end

    break if cost

  end

  puts cost

  puts 'Okay...any other hotels? (y/n)'  

  break unless gets.downcase.start_with?('y')    
end

而不是链式if / elsif / else / end我会使用case声明:

cost = case hotel
       when 'a' 
         (days / 3) * 500 + (days % 3) * 200
       when 'b'
         days * 250
       when 'c'
         (days / 3) * 700 + (days % 3) * 300
       when 'd'
         days * 500
       else
         puts 'Unknown hotel.'
       end