这似乎是验证数据输入的一种不好的方法。我发现自己做了很多事。有没有办法可以合并或简化程序?
Sub Main() ...
Console.Write("Landscape Size: ")
IsNumeric(LandscapeSize)
Console.Write("Initial number of warrens: ")
IsNumeric(InitialWarrenCount)
Validate(InitialWarrenCount, LandscapeSize)
Console.Write("Initial number of foxes: ")
IsNumeric(InitialFoxCount)
Validate(InitialFoxCount, LandscapeSize)
以下是两个似乎过于复杂的潜艇:
Sub IsNumeric(ByRef Variable As Integer)
While True
Try
Variable = CInt(Console.ReadLine())
Exit While
Catch
Console.WriteLine("Error: Please enter a number:")
End Try
End While
End Sub
Sub Validate(ByVal Variable As Integer, ByVal LandscapeSize As Integer)
Dim Size As Integer
Size = (LandscapeSize * LandscapeSize)
While Variable <= 0 Or Variable >= Size
Console.WriteLine("Error: Please enter a number:")
While True
Try
Variable = CInt(Console.ReadLine())
Exit While
Catch
Console.WriteLine("Error: Please enter a number:")
End Try
End While
End While
End Sub
非常感谢
答案 0 :(得分:1)
重命名IsNumeric .. 使用TryParse取代try catch
Sub ReadNumber(ByRef Variable As Integer)
Do
If Integer.TryParse(Console.ReadLine(), variable) Then Exit Sub
Console.WriteLine("Error: Please enter a number:")
Loop
End Sub
Sub Validate(ByVal Variable As Integer, ByVal LandscapeSize As Integer)
Dim Size As Integer = LandscapeSize * LandscapeSize
While Variable <= 0 Or Variable >= Size
Console.WriteLine("Error: Please enter a number:")
do
If Integer.TryParse(Console.ReadLine(), variable) Then Exit Do
Console.WriteLine("Error: Please enter a number:")
loop
End While
End Sub
但是......我猜你真的希望Validate中的第一个变量是ByRef NOT ByVal。