user12476460
user12476460

Reputation:

Cannot figure out while loop

I am trying to create a while loop in R, with the goal of having a user input a number, having the code print the corresponding entry based on the numeric position it has in the vector, continuing to offer another selection from the menu, and then breaking the loop if 6 is entered. I can get it to provide the right output in terms of the number that entered, but then it doesn't go back through the loop. (I made edits to the code based on comments below, but it still won't work the way I need it to)

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
  }
}

`

Upvotes: 0

Views: 49

Answers (1)

TimTeaFan
TimTeaFan

Reputation: 18581

Would the following work?

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
  }
}

Upvotes: 0

Related Questions