【问题标题】:How to display a message only after the third unsuccessful attempt in a function?如何仅在函数中第三次尝试失败后才显示消息?
【发布时间】:2020-11-17 14:15:32
【问题描述】:

以下代码包含使用函数式编程输入密码。

pw = 9999

for (i in 1:3){
pw_entered=as.numeric(readline("Please enter the password: "))

if (pw_entered==pw){
    print("The door is opened. Welcome!")
    break
    
} else {
    print("Password wrong. Please re-enter the password: ")
    
}
print("You have exceeded the maximum limit of three times. Try Later")
} 

输出是,

Please enter the password: 1
[1] "Password wrong. Please re-enter the password: "
[1] "You have exceeded the maximum limit of three times. Try Later"
Please enter the password: 2
[1] "Password wrong. Please re-enter the password: "
[1] "You have exceeded the maximum limit of three times. Try Later"
Please enter the password: 3
[1] "Password wrong. Please re-enter the password: "
[1] "You have exceeded the maximum limit of three times. Try Later"

我希望消息 You have exceeded the maximum limit of three times. Try Later 仅在第三次尝试失败后显示,而不是在第一次和第二次尝试失败后显示。

【问题讨论】:

    标签: r functional-programming


    【解决方案1】:

    我建议使用while 循环,因为不能保证每次都必须运行 3 次(如果在第一次尝试时输入的密码正确)。

    pw <- 9999
    attempt <- 0
    #Something which is not pw
    pw_entered <- 0
    
    while(pw_entered != pw && attempt < 3) {
       pw_entered = as.numeric(readline("Please enter the password: "))
       if (pw_entered==pw){
          print("The door is opened. Welcome!")
          break
       } 
       attempt <- attempt + 1
      if(attempt == 3)  {
         print("You have exceeded the maximum limit of three times. Try Later")
         break
      }
      else print("Password wrong. Please re-enter the password: ")
    } 
    
    #Round 1 - 
    Please enter the password: 123
    #[1] "Password wrong. Please re-enter the password: "
    Please enter the password: 9999
    #[1] "The door is opened. Welcome!"
    
    #Round 2 - 
    Please enter the password: 1234
    #[1] "Password wrong. Please re-enter the password: "
    Please enter the password: 21
    #[1] "Password wrong. Please re-enter the password: "
    Please enter the password: 23
    #[1] "You have exceeded the maximum limit of three times. Try Later"
    

    【讨论】:

    • 只要输入正确的密码,break 就会停止 for 循环
    • 这不是预期的吗?或者您打算在输入正确密码后继续尝试?
    • 我的意思是 for 循环将具有与 while 相同的行为,因为它会在 break 后停止
    猜你喜欢
    • 2015-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-13
    • 2015-02-23
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    相关资源
    最近更新 更多