Reputation: 167
What is the best way to Y/Yes and 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
Upvotes: 1
Views: 776
Reputation: 54417
I would implement it like this:
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
Note that I have the condition the right way around, i.e. if the want to play again then I do not exit the game and vice versa.
Note also that, by using ReadKey
, the user doesn't have to press the Enter key and they can't mistakenly waste their time typing "yes" when only "y" is required and they can't type something ambiguous like "yikes". Don't make the user do more than is necessary.
Upvotes: 3
Reputation: 8591
Try this:
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
For further details, please see:
Upvotes: 1