如何重复条件语句直到选择正确?

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

How to repeat the conditional statement until the choice is correct?

问题

在这段代码中,我试图在条件为假或默认时再次重复 if 语句,但循环在默认情况下停止。

  1. 如果我在循环内部写入 Scanln,它不会让我输入数据。
  2. 如果我在循环外部写入 Scanln,它不会重复执行循环。

如何重复执行循环,直到我输入正确的选择?

  1. package main
  2. import "fmt"
  3. func main() {
  4. var choice int
  5. fmt.Printf("Enter your choice: ")
  6. _, err := fmt.Scanln(&choice)
  7. if err != nil {
  8. fmt.Println("Letters or symbols not accepted")
  9. }
  10. for choice == 1 || choice == 2 {
  11. switch choice {
  12. case 1:
  13. fmt.Println("1 is selected")
  14. case 2:
  15. fmt.Println("2 is selected")
  16. default:
  17. fmt.Printf("Please enter the correct choice: ")
  18. }
  19. }
  20. }
英文:

In this code, I am trying to repeat the if-statement again if the condition is false or default but the loop stops at the default.

  1. If I write Scanln inside the loop then it does not let me input the data
  2. If I write Scanln outside the loop then it does not repeat the loop.

How to repeat the loop again and again until I enter the correct choice?

  1. package main
  2. import "fmt"
  3. func main() {
  4. var choice int
  5. fmt.Printf("Enter your choice: ")
  6. _, err := fmt.Scanln(&choice)
  7. if err != nil {
  8. fmt.Println("Letters or symbols not accepted")
  9. }
  10. for choice == 1 || choice == 2 {
  11. switch choice {
  12. case 1:
  13. fmt.Println("1 is selected")
  14. case 2:
  15. fmt.Println("2 is selected")
  16. default:
  17. fmt.Printf("Please enter the correct choice: ")
  18. }
  19. }
  20. }

答案1

得分: 1

以下脚本将完成您的工作。

  1. package main
  2. import "fmt"
  3. func main() {
  4. var choice int
  5. for choice != 1 || choice != 2 {
  6. fmt.Printf("请输入您的选择:")
  7. _, err := fmt.Scanln(&choice)
  8. if err != nil {
  9. fmt.Println("不接受字母或符号")
  10. }
  11. switch choice {
  12. case 1:
  13. fmt.Println("选择了1")
  14. case 2:
  15. fmt.Println("选择了2")
  16. default:
  17. fmt.Printf("请输入正确的选择:")
  18. }
  19. }
  20. }

希望对您有帮助!

英文:

Below script will get your work done.

  1. package main
  2. import "fmt"
  3. func main() {
  4. var choice int
  5. for choice != 1 || choice != 2 {
  6. fmt.Printf("Enter your choice: ")
  7. _, err := fmt.Scanln(&choice)
  8. if err != nil {
  9. fmt.Println("Letters or symbols not accepted")
  10. }
  11. switch choice {
  12. case 1:
  13. fmt.Println("1 is selected")
  14. case 2:
  15. fmt.Println("2 is selected")
  16. default:
  17. fmt.Printf("Please enter the correct choice: ")
  18. }
  19. }
  20. }

huangapple
  • 本文由 发表于 2022年8月23日 13:37:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/73453619.html
匿名

发表评论

匿名网友

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

确定