2014-11-17 17 views
-1

我试图让遍历if语句,如果用户输入无效它都跟只输入数字或断裂,如果真的红宝石使用,如果内环路与用户输入

我想这是我的代码

class String 
    def numeric? 
    Float(self) != nil rescue false 
    end 
end 
cond = false 

puts "Enter number " 
line = gets.chomp.strip 

while cond == false 
    if (line.numeric? ) 
     puts "Ok nice " 
     cond = true 
     else 
     puts "Please enter number only " 

    end 
end 

但它一直循环,如果条件是假的只是印刷“请输入号码只有”

我会为任何建议非常高兴

谢谢

+1

你不要求另一条线路。 –

回答

1

的问题是,告诉用户只需要输入一个号码后,你不读另一个号码,您只需循环回到我的身边。

解决这个问题的最简单方法是在提示,输入移动到while环,有点像这样:

class String 
    def numeric? 
    Float(self) != nil rescue false 
    end 
end 
cond = false 

while cond == false 
    puts "Enter number " 
    line = gets.chomp.strip 

    if (line.numeric? ) 
     puts "Ok nice " 
     cond = true 
    else 
     puts "Please enter number only " 
    end 
end 
0

试试这个:

while cond == false 
    if (line.numeric? ) 
     puts "Ok nice " 
     cond = true 
    else 
     puts "Please enter number only " 
     line = gets.chomp.strip 
    end  
end 
0

右覆盖字符串方法后,试试这个:

while true                                                    
    print "Enter number "                                               
    line = gets.chomp.strip 

    if line.numeric? 
    puts "Ok nice" 
    break 
    else 
    puts "Please enter number only" 
    end                                               
end