while()循环即使输入有效也不会中断

时间:2019-06-01 15:58:47

标签: r

我正在关注一个YouTube视频,该视频正在经历如何在R中创建交互式菜单。我确实从原始视频中进行了一些调整,但是没有任何东西会破坏或破坏代码(至少我是这么认为的)。

我观看的youtube视频:

https://www.youtube.com/watch?v=uaPBpJArh0M

弹出菜单,我尝试输入非零值。但是,尽管输入了有效的非零值,但循环仍在继续中断

Please choose a menu item: 1
Please choose a menu item: 2
Please choose a menu item: 3
Please choose a menu item: 4
Please choose a menu item: 5
Please choose a menu item: 6
Please choose a menu item: 7

似乎起作用的特定功能是代码的这一部分:

inputNumber <- function(prompt) {
  # Usage: num = inputNumber(prompt)
  # 
  # Displays prompt and asks for a number. 
  # Repeats until user inputs a valid number.
  while(TRUE) {
    num = suppressWarnings(as.numeric(readline(prompt)))
    if(!is.na(num)) {
      break
    }
  }
}

displayMenu <- function(options) {
  # Usage: choice = displayMenu(options)
  # 
  # Displays a menu of options,
  # ask the user to choose an item,
  # and return the number of the menu item chosen.
  # 
  # Input   options   Menu options (cell array of strings)
  # Output  choice    Chosen option (integer)

  # Display menu options
  for (i in 1:length(options)) {
    cat(sprintf("%d. %s\n", i, options[i]))
  }

  # Gets a valid menu choice
  choice <- 0
  while (!any(choice == 1:length(options))) {
    choice = inputNumber("Please choose a menu item: ")
  }

  return(choice)
}

# Define menu options
menuItems   <- c("Binomial", "Poisson", "Geometric", "Negative Binomial", "Hypergeometric", "Uniform", "Normal", "Exponential")

  # Displays the menu
  choice <- displayMenu(menuItems)

  if(choice == 1) {
    print("Good choice!")
  } else {
    print("Bad choice.")
  }

1 个答案:

答案 0 :(得分:0)

inputNumber函数未返回任何内容,您只是在不为其分配值的情况下就将其断开。改用return,它将停止一段时间,并向函数调用返回一个值。

inputNumber <- function(prompt) {
  # Usage: num = inputNumber(prompt)
  # 
  # Displays prompt and asks for a number. 
  # Repeats until user inputs a valid number.
  while(TRUE) {
    num = suppressWarnings(as.numeric(readline(prompt)))
    if(!is.na(num)) {
      return(num)
    }
  }
}

displayMenu <- function(options) {
  # Usage: choice = displayMenu(options)
  # 
  # Displays a menu of options,
  # ask the user to choose an item,
  # and return the number of the menu item chosen.
  # 
  # Input   options   Menu options (cell array of strings)
  # Output  choice    Chosen option (integer)

  # Display menu options
  for (i in 1:length(options)) {
    cat(sprintf("%d. %s\n", i, options[i]))
  }

  # Gets a valid menu choice
  choice <- 0
  while (!any(choice == 1:length(options))) {
    choice = inputNumber("Please choose a menu item: ")
  }

  return(choice)
}

# Define menu options
menuItems   <- c("Binomial", "Poisson", "Geometric", "Negative Binomial", "Hypergeometric", "Uniform", "Normal", "Exponential")

# Displays the menu
choice <- displayMenu(menuItems)

if(choice == 1) {
  print("Good choice!")
} else {
  print("Bad choice.")
}