输入Yes/Y和No/nvb.Net控制台

Input Yes/Y and No/n vb.Net console

Y/Yes 和 N/No 的最佳方式是什么?

Private Function ExitGame() As Boolean

    Dim input As String = ""

    Do
        If input <> "yes" And input <> "no" Then
            Console.WriteLine("Would you like to play again ('yes' or 'no')?")
            input = Console.ReadLine().ToLower()
        ElseIf input <> "y" And input <> "no" Then
            Console.WriteLine("Would you like to play again ('yes' or 'no')?")
            input = Console.ReadLine().ToLower()
        End If
    Loop
    Return input = "yes"

End Function

试试这个:

Private Function ExitGame() As Boolean
    Dim input As String = String.Empty

    Do While input = String.Empty
        Console.WriteLine("Would you like to play again ('yes[y]' or 'no[n]')?")
        input =  Console.ReadLine().ToLower()
        Dim r As Regex = New Regex("[y|n]")
        If Not r.IsMatch(input) Then input = String.Empty
    Loop
    Return input = "y"
End Function

详情请见:

StartsWith

Substring

Regex

我会这样实现:

Module Module1

    Sub Main()
        Do
            Console.WriteLine("play, play, play")
        Loop Until ExitGame()
    End Sub

    Private Function ExitGame() As Boolean
        Do
            Console.Write("Would you like to play again ([Y]es/[N]o)? ")

            Dim key = Console.ReadKey().Key

            Console.WriteLine()

            Select Case key
                Case ConsoleKey.Y
                    'Play again and do not exit game.
                    Return False
                Case ConsoleKey.N
                    'Exit game without playing again.
                    Return True
            End Select
        Loop
    End Function

End Module

请注意,我的条件是正确的,即如果想再次玩游戏,那么我不会退出游戏,反之亦然。

另请注意,通过使用 ReadKey,用户不必按 Enter 键,他们不会错误地输入“是”浪费时间" 当只需要 "y" 并且他们不能输入像 "yikes" 这样模棱两可的东西时。不要让用户做不必要的事情。