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

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

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

问题

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

  1. 如果我在循环内部写入 Scanln,它不会让我输入数据。
  2. 如果我在循环外部写入 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: ")
        }
    }
}
英文:

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?

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: ")
		}
	}
}

答案1

得分: 1

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

package main

import "fmt"

func main() {
    var choice int

    for choice != 1 || choice != 2 {
        fmt.Printf("请输入您的选择:")
        _, err := fmt.Scanln(&choice)
        if err != nil {
            fmt.Println("不接受字母或符号")
        }
        switch choice {
        case 1:
            fmt.Println("选择了1")
        case 2:
            fmt.Println("选择了2")
        default:
            fmt.Printf("请输入正确的选择:")
        }
    }
}

希望对您有帮助!

英文:

Below script will get your work done.

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: ")
		}
	}
}

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:

确定