我希望你能帮助我一点:
var characters1 = [Character]()
func selectCharacterScreen1() {
var name: String = ""
var error: Bool = false
repeat {
if error == true {
print("Please type a valid character's name. His name must be unique.")
}
else {
print("Please type an unique character's name")
}
name = inputString()
error = false
for c in characters1 {
if c.nameCharacter == name {
error = false
break
}
}
} while error == true
}
我希望代码必须检查字符的名称是否都是唯一的。如果没有,代码必须拒绝,用户必须重新键入另一个字符的名称。在此代码中,您可以输入字符的名称,但代码并不关心字符的名称是否唯一。
答案 0 :(得分:0)
首先,列表应该包含字符串,而不是字符,其次,你的代码在这里很不清楚:
repeat {
if error == true {
print("Please type a valid character's name. His name must be unique.")
}
else {
print("Please type an unique character's name")
}
name = inputString()
error = false
for c in characters1 {
if c.nameCharacter == name {
error = false
break
}
}
} while error == true
你在error = false(在for循环中)的想法中有一个基本的缺陷。如果名称匹配为非唯一,则应将error设置为true。
如果您只想输入一个名称并检查该名称是否已经在Characters1列表中,那么将for循环更改为如下所示:
for c in characters1 {
if c == name {
error = true # it has to set error to true so the for loop rejects the name and restarts
break
}
}
if error == false {
characters1.append(name)
}
此代码适用于一名玩家。如果你想输入3个名字,把整个重复循环放在for循环中,看起来像这样:
var characters1 = [String]()
func selectCharacterScreen1() {
var name: String = ""
var error: Bool = false
for x in 1...3{
repeat {
if error == true {
print("Please type a valid character's name. His name must be unique.")
}
else {
print("Please type an unique character's name")
}
name = inputString
error = false
for c in characters1 {
if c == name {
error = true
break
}
}
if error == false {
characters1.append(name)
}
} while error == true
}
}
我试过这个,它对我有用。如果你不明白,请告诉我