英文:
User input within while loop before continuing with while loop execution
问题
我正在使用Swift构建一个包含人类和计算机玩家的投注循环。我基本上将代码结构化如下所示:
let ls = [1, 2, 3, 4, 5]
var x = 1
while x < 35 {
for i in ls {
if i == 1 {
x += 1
}
if i == 2 {
x += 1
}
if i == 3 {
x += 1
}
if i == 4 {
// 询问用户要增加多少
print("输入要增加的数量:")
if let input = readLine(), let increment = Int(input) {
x += increment
} else {
print("无效输入")
}
}
if i == 5 {
x += 1
}
}
}
while循环在继续执行循环的其余部分之前不会暂停等待用户输入。我尝试过创建一个Thread并使用信号量,但没有成功。如何以“正确”的方式实现这种目标?
英文:
I'm building a betting loop with a human and computer players in Swift. I essentially have the code structured as follows:
let ls = [1, 2, 3, 4, 5]
var x = 1
while x < 35 {
for i in ls {
if i == 1 {
x += 1
}
if i == 2 {
x += 1
}
if i == 3 {
x += 1
}
if i == 4 {
// ask user how much to increment by
print("Enter the amount to increment by:")
if let input = readLine(), let increment = Int(input) {
x += increment
} else {
print("Invalid input")
}
}
if i == 5 {
x += 1
}
}
}
The while loop doesn't pause to wait for a user input before carrying on with the rest of the loop. I've tried creating a Thread and using semaphores but have had no luck. What is the "proper" way to achieve this type of goal?
答案1
得分: 1
你可以为readLine
逻辑添加一个循环,这样外部循环将不会继续,直到输入了正确的值。
if i == 4 {
print("输入要增加的数量:")
while let input = readLine() {
if let increment = Int(input) {
x += increment
break
} else {
print("无效的输入")
}
}
}
英文:
You can have a loop just for the readLine logic so the outer loop will not continue until a correct value has been entered
if i == 4 {
print("Enter the amount to increment by:")
while let input = readLine() {
if let increment = Int(input) {
x += increment
break
} else {
print("Invalid input")
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论