【发布时间】: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 <- readline(prompt = paste(menu, "Please select an item from the menu: ")) -
是的,没错。我不确定如何解决它。
-
另外,为什么需要
while循环。它可以是switch或if/else if/else。如果您注意条件,每当您选择 x 不等于 6 时,它将无限循环
标签: r vector while-loop