【问题标题】:Re-prompt readline() if the input is invalid如果输入无效,重新提示 readline()
【发布时间】:2022-01-21 01:42:27
【问题描述】:

假设我想要求用户输入一个超过 10 的数字。如果没有,请打印一条消息并重新提示/再次询问。这如何在 R 中实现? 我知道这可以通过 IF 或 WHILE 语句来解决,但我无法解决这个问题。

例子

math <- function(number_1) {

  number_1 <- readline("Enter your number: ")
  if the number is below i want to reprompt readline(...)
  
  result <- number_1 / 2 
  
  return(result)
}

【问题讨论】:

    标签: r readline


    【解决方案1】:

    这是一种方法:

    math <- function() {
    
      result <- NA
    
      while (is.na(result) || result < 10) {
        text <- readline("Enter your number: ")
        result <- as.numeric(text)
      }
      
      result
    }
    

    你不需要为你的函数提供任何输入;它会在提示用户时获取输入。 is.na(result) 代码检查 NA:最初的结果是 NA,所以它会至少运行一次循环,如果 用户输入的不是数字,你会得到另一个。

    由于readline()返回的是字符值,所以需要as.numeric将其转换为数字。

    【讨论】:

      猜你喜欢
      • 2020-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-14
      • 2017-07-29
      • 1970-01-01
      • 2013-12-12
      相关资源
      最近更新 更多