我正在为课程作业创建座位预订计划,用户可以选择他/她希望预订座位的行,然后是他们希望预订的座位数。
Public Class Form1
Private Sub ListBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox2.SelectedIndexChanged
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim rowNumber As Integer
Dim SeatsData As String(,) = {{"booked", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "A10"}, {"booked", "booked", "booked", "booked", "booked", "booked", "booked", "booked", "booked", "booked"}, {"C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "C10"}, {"D1", "booked", "booked", "D4", "D5", "D6", "D7", "D8", "D9", "D10"}, {"E1", "E2", "booked", "booked", "booked", "E6", "E7", "E8", "E9", "E10"}}
If ListBox2.Text = "A" Then
rowNumber = 0
ElseIf ListBox2.Text = "B" Then
rowNumber = 1
ElseIf ListBox2.Text = "C" Then
rowNumber = 2
ElseIf ListBox2.Text = "D" Then
rowNumber = 3
ElseIf ListBox2.Text = "E" Then
rowNumber = 4
End If
FindSeats(rowNumber, ListBox1.Text, SeatsData)
End Sub
Function FindSeats(ByVal RowNumber As Integer, ByVal NumSeats As Integer, SeatsData As Array) As String
Dim i As Integer = 0
Dim arrayPos As Integer = 0
Dim largestStreak As Integer = 0
Dim FirstSeat As String = 0
Dim LastSeat As String = 0
Dim foundSeats As Boolean = False
Dim returnMsg As String = ""
Do While foundSeats = False
Dim seatChar As String = SeatsData(RowNumber, arrayPos)
arrayPos = arrayPos + 1
If seatChar = "booked" Then
i = 0
Else
If i = 0 Then
FirstSeat = seatChar
End If
i = i + 1
If i > largestStreak Then
largestStreak = i
End If
End If
If i = NumSeats Then
LastSeat = seatChar
If FirstSeat = LastSeat Then
returnMsg = "Found seat: " + FirstSeat
Else
returnMsg = "Found seats: " + FirstSeat + " - " + LastSeat
End If
MsgBox(returnMsg)
Label3.Text = returnMsg
foundSeats = True
Exit Do
End If
If arrayPos = 10 Then
returnMsg = "Not enough available seats, maximum available seats: " + CStr(largestStreak)
MsgBox(returnMsg)
Label3.Text = returnMsg
Exit Do
End If
Loop
End Function
End Class
我遇到的问题是当用户选择他们想要的座位数而不是他们想要的那一行时,该程序会自动预订A行中的座位。如何解决这个问题?此外,当用户选择一行而不是多个席位(反之亦然)时,表单将转到代码并输出以下错误消息:"未处理的类型' System.InvalidCastException'发生在Microsoft.VisualBasic.dll
其他信息:从字符串转换""输入'整数'无效。"
如何解决这些错误?我是VB的新手,所以如果有任何明显的话,那么我道歉!
答案 0 :(得分:3)
你得到例外是因为你这样叫FindSeats
:
FindSeats(rowNumber, ListBox1.Text, SeatsData)
请注意FindSeats
的签名实际上是
Function FindSeats(RowNumber As Integer, NumSeats As Integer, SeatsData As Array) As String
因此,您将ListBox1.Text
字符串作为NumSeats
参数传递,该参数为Integer
。由于您使用Option Strict Off
,VB.Net会尝试将ListBox1.Text
中的字符串隐式转换为Integer
。
如果ListBox1.Text
为空,则会失败,这就是它告诉您的异常消息:
从字符串“”到“整数”类型的转换无效。
首先,将Option Strict
转为On
,然后您将看到所有那些在运行时会咬你的漂亮的隐式转换。继续使用有意义的安全显式转换替换它们。
在用户点击Button1
而不选择ListBox1
之前的内容时,请考虑如何处理此案例。
也许您想使用Int32.TryParse
来处理此类情况,或者可能在ListBox1