Rich Rich - 4 years ago 79
Vb.net Question

Validating Data Entry

This seems like such a poor way of validating data entry. Something that I find myself doing a lot. Is there a way the procedures can be combined or simplified?

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)


And here are the two subs which seem overly complex:

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


Many thanks

Answer Source

So rename the IsNumeric.. Get rid of the try catch using TryParse instead

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

HOWEVER.. I'm guessing you really wanted that first variable in the Validate to be ByRef NOT ByVal.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download