用户在 while 循环之前输入,然后继续执行 while 循环。

huangapple go评论49阅读模式
英文:

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 &lt; 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(&quot;Enter the amount to increment by:&quot;)
            if let input = readLine(), let increment = Int(input) {
                x += increment
            } else {
                print(&quot;Invalid input&quot;)
            }
        }
        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(&quot;Enter the amount to increment by:&quot;)
    while let input = readLine() {
        if let increment = Int(input) {
            x += increment
            break
        } else {
            print(&quot;Invalid input&quot;)
        }
    }
}

huangapple
  • 本文由 发表于 2023年4月17日 22:24:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76036196.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定