Reputation: 167
This one's really got me confused. I'm trying to do a visual basic console application that if the user enters 'A' or 'a' then the program should do 'x', but that's not working. The error I get is:
Conversion from string "a" to type 'Boolean' is not valid.
Here's my code:
Module Module1
Sub Main()
Dim Selection As String
Console.WriteLine("Please select your function:")
Console.WriteLine("* To convert binary to decimal, press A,")
Console.WriteLine("* Or to convert decimal to binary, press B")
Selection = Console.ReadLine
If Selection = "A" Or "a" Then
Console.WriteLine("This will be A")
ElseIf Selection = "B" Or "b" Then
Console.WriteLine("This will be B")
ElseIf Selection = Not "A" Or "a" Or "B" Or "b" Then
Console.WriteLine("Please try again")
Do Until Selection = "A" Or "a" Or "B" Or "b"
Loop
End If
End Sub
What should be the correct usage of the Or in this piece of code to make it function correctly?
Upvotes: 2
Views: 19905
Reputation: 10780
Using Select Case is yet another alternative:
Sub Main()
Console.WriteLine("Please select your function:")
Console.WriteLine("* To convert binary to decimal, press A,")
Console.WriteLine("* Or to convert decimal to binary, press B")
Console.WriteLine("* To Quit, press Q")
Dim Selection As String = ValidateInput()
If Selection <> "Q" Then
'do something
End If
End Sub
Function ValidateInput() As String
Dim Selection As String
Selection = Console.ReadLine
Select Case Selection.ToUpper
Case "A"
Console.WriteLine("This will be A")
Case "B"
Console.WriteLine("This will be B")
Case "Q"
Return "Q"
Case Else
Console.WriteLine("Please try again")
ValidateInput()
End Select
Return Selection
End Function
Upvotes: 3
Reputation: 7493
I would suggest changing the string entered into upper case before the if statements. Also the last else if statement isn't needed and can be replaced with a single else.
Sub Main()
Dim Selection As String
Console.WriteLine("Please select your function:")
Console.WriteLine("* To convert binary to decimal, press A,")
Console.WriteLine("* Or to convert decimal to binary, press B")
Selection = Console.ReadLine.ToUpper() 'Not tested otherwise use the one below
'Selection=Selection.ToUpper()
If Selection = "A" Then
Console.WriteLine("This will be A")
ElseIf Selection = "B" Then
Console.WriteLine("This will be B")
Else
Do Until Selection = "A" Or Selection = "B"
'Loop Code goes here
Loop
End If
End Sub
Upvotes: 3
Reputation: 498982
Your If
clauses should be like:
If Selection = "A" Or Selection = "a" Then
The clauses between the Or
should each be boolean expressions, and "a"
is simply a character, not a boolean expression.
Upvotes: 5