【问题标题】:Robust match of user input in a while loop在while循环中用户输入的稳健匹配
【发布时间】:2020-04-30 17:34:29
【问题描述】:
while(not_match){
    if(r==1){
      print("Name Player 1: ")
      name1=scan(,what="character",1)
}
}

大家好,我希望当用户在代码询问玩家 1 的姓名时输入“回车”时,代码会显示类似:“此名称无效”,然后重复询问玩家 1 的姓名。我知道我必须使用类似:if(length(name1==0))...但我不知道如何让代码重复询问 name1。希望您能够帮助我。谢谢。

【问题讨论】:

    标签: r


    【解决方案1】:

    这种方法应该适合你

    name = readline("Player name: >")
    while (!stringr::str_detect("[a-z]", tolower(name)) | name == ""){
      name = readline("Player name: >")
    }
    

    这可能有点矫枉过正,但如果您事先知道玩家的姓名,您可以使用choices 包。目前,仅在 GitHub 上可用并通过

    安装
    devtools::install_github("matiasandina/choices")
    
    library(choices)
    players <- c("Alice", "Bob", "Chris")
    numeric_menu(players, "Select Player")
    

    您将看到菜单,您可以选择使用数字。

    +++++++++++++++++++++++++++++++
    Please see your options below:
    +++++++++++++++++++++++++++++++
    Option 1) Alice
    Option 2) Bob
    Option 3) Chris
    
    Select Player :> 
    

    内部函数将负责将数字与存储的播放器选项进行匹配。此外,“Enter”键或猫敲击键盘也很强大

    Name Player :> sdkjaksdjaksd
    Your input is not valid, please enter a number.
    Name Player :> kasdjlaksjdlkasasdma
    Your input is not valid, please enter a number.
    Name Player :> 
    Your input is not valid, please enter a number.
    Name Player :> ?
    Your input is not valid, please enter a number.
    Name Player :> 54
    Option is not valid. Choose again
    Name Player :> 
    

    免责声明:我是选择包的作者,更多信息here

    【讨论】:

    • 谢谢,但我不能使用外部包。
    • 好吧...如果您只想检查“Enter”,您可以将您的条件更改为仅name == "" 并且不涉及任何包
    猜你喜欢
    • 1970-01-01
    • 2013-11-16
    • 2020-02-15
    • 1970-01-01
    • 1970-01-01
    • 2015-07-03
    • 1970-01-01
    • 2016-01-11
    • 2016-05-20
    相关资源
    最近更新 更多