I created a project for a programming class that asks you to make a userform in Visual Studio that calculates mileage, given the user inputs of gallons of gas consumed and distance traveled. The code does its job fine, but I can't help but feel that my use of Do...While and Try...Catch statements are less than elegant. If anyone has suggestions or tips or cryptic hints about what would improve my code, I would be grateful!
Private Sub btnMileage_Click(sender As Object, e As EventArgs) Handles btnMileage.Click Dim sngGas As Single, sngDistance As Single, sngMileage As Single Do While sngGas <= 0 'force user to input positive number for gallons of gas consumed Try 'reject all inputs that are not real numbers sngGas = CSng(InputBox("Please enter gasoline consumed in gallons:")) If sngGas <= 0 Then 'remind user to input number greater than 0 MsgBox("Please make sure your input is greater than 0.") End If Catch ex As Exception MsgBox("Error: Please enter a valid number.") 'remind user that all inputs that aren't numbers are rejected End Try Loop Do While sngDistance <= 0 Try 'reject all inputs that are not real numbers sngDistance = CSng(InputBox("Please enter distance travelled in miles:")) 'force user to enter positive value for distance If sngDistance <= 0 Then MsgBox("Please make sure your input is greater than 0.") End If Catch ex As Exception MsgBox("Error: Please enter a valid number.") 'reminder user that all inputs that aren't numbers are rejected End Try Loop sngMileage = Math.Round((sngDistance / sngGas), 1, MidpointRounding.AwayFromZero) 'calculate mileage PopulateForm(CStr(sngGas), CStr(sngDistance), CStr(sngMileage)) 'update form with gas, distance & mileage MsgBox("All done!") End Sub
The sub I use to populate the form follows:
Private Sub PopulateForm(Optional ByVal strGas As String = "", Optional ByVal strDistance As String = "", Optional ByVal strMileage As String = "") 'wipes form or populates with new values lblGas.Text = "Gas Consumed: " & strGas lblDistance.Text = "Distance Travelled: " & strDistance lblMileage.Text = "Mileage: " & strMileage End Sub