这个让我很困惑。我正在尝试做一个可视化的基本控制台应用程序,如果用户输入'A'或'a',那么程序应该执行'x',但这不起作用。我得到的错误是:
从字符串“a”到“布尔”类型的转换无效。
这是我的代码:
模块模块1
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
在这段代码中正确使用Or以使其正常运行应该是什么?
谢谢,
杰克
答案 0 :(得分:4)
您的If
条款应该是:
If Selection = "A" Or Selection = "a" Then
Or
每个之间的子句应该是布尔表达式,而"a"
只是一个字符,而不是布尔表达式。
答案 1 :(得分:3)
我建议在if语句之前更改输入大写的字符串。此外,不需要最后一个if语句,可以用一个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
答案 2 :(得分:3)
使用选择案例是另一种选择:
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