Reputation: 25
I am relatively new to programming, and am starting off with VB.net using Microsoft VB Studio 2019. I usually use Python, and therefore take heavy advantage of the
> If String in("y","yes","YES"):
statement so I don't have to compare the string to every item individually.
I've been trying to do this on Virtual Basic for some time now, but have not even managed to get 1 value to compare to the string to work. I've tried 2 different methods, the first just being a basic String.Contains() command, which I've set out as such:
Dim UserSelection As String
Console.Write("Play again? ")
UserSelection = Console.Read()
If UserSelection.Contains("n") = True Then
UserPlaying = False
End If
My thought process here was that the computer would look at UserSelection, and if it contained the letter 'n' at any point then it would result as being True (eg: if UserSelection = 'no', 'nope', 'n' ext ext) However, every time I've ran this code, the result always comes back as false, no matter what UserSelection is.
I've also tried using the IndexOf command (which makes the search case insensitive) to see if it would work then, but again something seems to be up with it:
Dim UserSelection As String
Console.Write("Play again? ")
UserSelection = Console.Read()
Dim subtxt As String = "n"
Dim comp As StringComparison = StringComparison.OrdinalIgnoreCase
Dim result As Boolean = If(UserSelection.IndexOf(subtxt, comp) > 0, True, False)
If result = True Then
UserPlaying = False
End If
My indentation appears correct in both blocks of code, and I cannot for the life of me figure out what it wrong here.
If someone could help me with this (especially if you could adjust the code so that it could work with multiple comparisons) then that would be more than appreciated.
Upvotes: 1
Views: 606
Reputation: 15091
I just added .ToLower to the UserSelection string before the Contains so N or n would be recognized.
Private UserPlaying As Boolean
Sub Main()
Console.Write("Play again? ")
Dim UserSelection = Console.ReadLine()
If UserSelection.ToLower.Contains("n") = True Then
Debug.Print("It contains n")
UserPlaying = False
Else
Debug.Print("No n")
UserPlaying = True
End If
Console.ReadKey()
End Sub
Upvotes: 0
Reputation: 6131
Console.Read returns an Integer (documentation), so naturally it would return false
. The method you're looking for is Console.ReadLine (documentation), which returns a string.
Take a look at this example:
Console.Write("Play again? ")
Dim input = Console.ReadLine()
Dim stopPlaying = input.IndexOf("n", StringComparison.OrdinalIgnoreCase) > -1
If (stopPlaying) Then
' the user replied with "n", "no", "nope", etc.
Else
' the user replied with something that did not contain the letter "n"
End If
Fiddle: https://dotnetfiddle.net/Fihq02
Upvotes: 1