r - 我对 R 中的“重复”功能有疑问
问题描述
checknames <- function(){
gamers <- c("Rebeca","Luis","Paco")
games <- c("3","2","7")
scores <- c(100,110,50)
table <- data.frame(gamers,games,scores)
r=0
p=0
repeat{
print("Name Player 1: ")
name1=scan(,what="character",1)
for(i in 1:length(gamers)){
if(name1==gamers[i]){
r=readline(prompt = "This player is already in the file. Would you like to change the name? \n 1. Yes \n 2. No \n Select an option: ")
}
}
if(r==2){
break
}
if(r==0){
gamers=c(gamers,name1)
name1 <- data.frame(gamers=name1,games="1",scores="100")
table <- rbind(table,name1)
break
}
}
table
repeat{
print("Name Player 2: ")
name2=scan(,what="character",1)
for(i in 1:length(gamers)){
if(name2==gamers[i]){
print("This player is already in the file. Would you like to change the name?")
r=scan(,what="character",1)
}
}
if(p=="No"){
break
}
if(p==0){
gamers=c(gamers,name2)
name2 <- data.frame(gamers=name2,games="1",scores="100")
table <- rbind(table,name2)
break
}
}
table
}
table <-checknames()
我正在做一个询问用户 2 名称的代码,它应该证明表是否有这个名称,如果没有,添加它,如果有这个名称,询问玩家他/她是否想更改它。
问题是当玩家说他想更改名称时,重复功能永远不会中断,我认为这是因为我分配了错误的东西(我分配了 r==2/r==0),那就是为什么重复功能仍在重复。
解决方案
我发现您的代码存在一些问题。我们将专注于repeat
您为玩家 2 编写的第二个循环。
首先,我们可以简化for(if(
用于检查名称是否已被占用的循环。通过一次检查所有列表而不是遍历整个索引。
if(any(name2==gamers)){
print("This player is already in the file. Would you like to change the name?")
r=scan(,what="character",1)
}
现在,继续解决您的一些问题。您将变量存储r
在扫描中,但您正在检查变量p
。您应该将上述代码块中的行更改为 read p=scan(,what="character",1)
。
此外,您现在遇到的情况是,如果您的 user2 输入了一个已经使用的名称,然后将其更改为其他名称,您的代码将永远不会让他们离开,因为您从未设置p
回0
. 这可以通过添加else { p=<-0 }
一行来解决。
以上所有更改都在这里为您汇总:
if(any(name2==gamers)){
print("This player is already in the file. Would you like to change the name?")
p=scan(,what="character",1)
} else {
p <- 0}
推荐阅读
- android - Android 错误:特定代码块中的“不是语句”
- react-admin - 我可以更改每条路线的 react-admin 布局吗?
- fortran - 赋值后的实际值与实际表达式不同
- angular - 从 OL OSM 中的图层源获取中心点
- python - C++ 和 Boost.Python - 如何向 python 公开变量并在循环中更新它?
- python - 如何让 conda 知道我的包的数据和配置文件在哪里
- php - PHP循环遍历多维数组
- api - Hotstar API 使用有状态架构吗?即使没有登录,它如何跟踪用户?
- python - 在递归中使用全局变量
- javascript - 用JS拖拽后显示图片