【问题标题】:Cannot figure out while loop无法弄清楚while循环
【发布时间】:2021-08-30 17:15:27
【问题描述】:

我正在尝试在 R 中创建一个 while 循环,目的是让用户输入一个数字,让代码根据它在向量中的数字位置打印相应的条目,继续从菜单,然后在输入 6 时中断循环。我可以让它根据输入的数字提供正确的输出,但是它不会通过循环返回。 (我根据下面的 cmets 对代码进行了编辑,但它仍然无法按我需要的方式工作)

menu <- "MENU: \n1. Science Fiction \n2. Computers and Technology \n3. Cooking \n4. Business \n5. Comics \n6. Exit"

menuV <- c("You selected Science Fiction. This is a fun topic.",
           "You selected Computers and Technology. This is a complex topic.",
           "You selected Cooking. This is a passionate topic.",
           "You selected Business. This is a serious topic.",
           "You selected Comics. This is an entertaining topic.")

x <- readline(prompt=paste(menu, "Please select an item from the menu: "))
x <- as.numeric(x)

while (x != 6){
  if(x >= 1 & x <= 7){
    print(menuV[x])
  } else if(x < 1 | x > 7) {
    print("Invalid entry. Please try again.")
  } else {
    print("You exited the menu.")
    break
  }
}

`

【问题讨论】:

  • 你的意思是menuV[x] 而不是menuV(x) 因为menuV 不是函数,'x' 似乎是从menuV 向量中提取相应元素的索引
  • 我确实尝试过,但它并没有解决我提到的问题。
  • 你的readline也有问题x &lt;- readline(prompt = paste(menu, "Please select an item from the menu: "))
  • 是的,没错。我不确定如何解决它。
  • 另外,为什么需要while 循环。它可以是switch 或if/else if/else。如果您注意条件,每当您选择 x 不等于 6 时,它将无限循环

标签: r vector while-loop


【解决方案1】:

以下是否可行?

menu <- "MENU: \n1. Science Fiction \n2. Computers and Technology \n3. Cooking \n4. Business \n5. Comics \n6. Exit"

menuV <- c("You selected Science Fiction. This is a fun topic.",
           "You selected Computers and Technology. This is a complex topic.",
           "You selected Cooking. This is a passionate topic.",
           "You selected Business. This is a serious topic.",
           "You selected Comics. This is an entertaining topic.")

x <- readline(prompt = paste(menu, "Please select an item from the menu: "))

x <- as.numeric(x)


while (is.numeric(x)) {
  if(x >= 1 & x <= 5){
    print(menuV[x])
    x <- as.numeric(readline(prompt = paste(menu, "Please select an item from the menu: ")))
  } else if(x < 1 | x >= 7) {
    print("Invalid entry. Please try again.")
    x <- as.numeric(readline(prompt = paste(menu, "Please select an item from the menu: ")))
  } else {
    print("You exited the menu.")
    break
  }
}

【讨论】:

  • 感谢您抽出宝贵时间提供回复!这并不能完成我所需要的。它仍然不会在每次输入后继续循环提供菜单选择/输入,并且在输入 6 时不提供消息(即“您已退出菜单”)或中断循环。
  • @MameGannon-Luiz:好的,现在我想我明白循环应该做什么了,请查看我的更新答案。
  • 这太近了!它确实会中断,并满足所有其他要求,但在中断之前打印字符串除外。
  • 不确定,它没有,因为我们以while(x != 6) 开头。我刚刚注意到自己;)
  • 我现在将 while 语句更改为 is.numeric(x),但这使得整个 while 部分有点奇怪,因为我们没有像经典的 while 示例那样遍历数字。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-06
  • 2014-02-16
  • 2019-09-15
  • 2013-10-07
  • 2023-03-25
相关资源
最近更新 更多