Thorgo
Thorgo

Reputation: 1

VB.net <> math function

i am trying to make the below VB.net math function work. Currently when i enter a kpa valve > 7 the number should be multiplied by 1.5. It just produces the same number. Please note the system pressure is enter in by the user. I have re posted the full code,

Private Sub Calculate_Click(sender As Object, e As EventArgs) Handles Calculate.Click
    Try
        Dim kpa As Double = CDbl(SystemPressure.Text)
        If kpa > 0 AndAlso kpa <= 7 Then
            TestPressure.Text = kpa
        ElseIf kpa > 7.1 Then
            TestPressure.Text = 1.5 * kpa
        End If

        Dim dia = ComboBox1.Text
        Dim length As Double = CDbl(LengthMeters.Text)
        Dim area As Double = 3.142 * ((dia * 0.5 / 1000) ^ 2)
        Dim volume As Double = Math.Round(length * area, 2)
        Dim litres As Double = volume * 1000
        Dim minutes As Double = Math.Round((litres / 30) * 5, 0)
        Dim hours As Double = Math.Round((minutes / 60), 2)

        LabelVolume.Text = volume.ToString & " : Meters Cubed"
        TestPressure.Text = kpa & " : Kpa"
        TestTimeMinutes.Text = minutes.ToString & " : Minutes"
        TestTimeHours.Text = hours.ToString & " : Hours"

    Catch
        MessageBox.Show("Error: Enter numbers only", "Error")
        LengthMeters.Clear()
        SystemPressure.Clear()
        ComboBox1.Focus()
    End Try

End Sub

Private Sub clear_Click(sender As Object, e As EventArgs) Handles Clear.Click
    ComboBox1.ResetText()
    SystemPressure.Clear()
    LengthMeters.Clear()
    LabelVolume.Text = "Volume"
    TestTimeMinutes.Text = " : Minutes"
    TestTimeHours.Text = " : Hours"
    TestPressure.Text = "Kpa"


End Sub

Upvotes: 0

Views: 197

Answers (1)

Matt Wilko
Matt Wilko

Reputation: 27342

I would suggest that you need to program a bit more defensively.

I recommend that you check the value being input before trying to process it. Also a Select Case would make more sense to catch unexpected values (this will probably lead you to find your bug)

Something like this:

Dim kpa As Double

If Double.TryParse(SystemPressure.Text, kpa) Then
    Select Case kpa
        Case 0 To 7
            TestPressure.Text = kpa.ToString
        Case Is > 7.1
           TestPressure.Text = (1.5 * kpa).ToString
        Case Else
            Throw New Exception(String.Format("The input value {0} was an invalid value", kpa))
    End Select
Else
    Throw New Exception(String.Format("The input value {0} is not a numeric value", kpa))
End If

Also you should switch Option Strict On it will help you in the long run

Upvotes: 2

Related Questions