如何持续尝试直到选择正确条件语句?
时间:2024-02-12
浏览:241
作者:佚名
今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《如何持续尝试直到选择正确条件语句?》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!
问题内容
在这段代码中,如果条件为 false 或默认,我会尝试再次重复 if 语句,但循环会在默认值处停止。
- 如果我在循环内写入
scanln那么它不会让我输入数据 - 如果我在循环之外编写
scanln那么它不会重复循环。
如何一次又一次地重复循环,直到输入正确的选择?
package main
import "fmt"
func main() {
var choice int
fmt.Printf("Enter your choice: ")
_, err := fmt.Scanln(&choice)
if err != nil {
fmt.Println("Letters or symbols not accepted")
}
for choice == 1 || choice == 2 {
switch choice {
case 1:
fmt.Println("1 is selected")
case 2:
fmt.Println("2 is selected")
default:
fmt.Printf("Please enter the correct choice: ")
}
}
}正确答案
下面的脚本将完成您的工作。
package main
import "fmt"
func main() {
var choice int
for choice != 1 || choice != 2 {
fmt.Printf("Enter your choice: ")
_, err := fmt.Scanln(&choice)
if err != nil {
fmt.Println("Letters or symbols not accepted")
}
switch choice {
case 1:
fmt.Println("1 is selected")
case 2:
fmt.Println("2 is selected")
default:
fmt.Printf("Please enter the correct choice: ")
}
}
}以上就是《如何持续尝试直到选择正确条件语句?》的详细内容,更多关于的资料请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
