r/visualbasic • VB.Net Beginner • Oct 14 '20

Stumped with formula in code.

Apologies in advance if a) I come off as a total noob (I'm new to Visual Basic) and b) if this post is rather long. TL;DR: I need to calculate BMI using the values entered into the textbox objects I'm using and spit out the answer onto one of the labels.

So I find myself stumped on setting up a set of calculations to determine Body Mass Index (BMI) using either English units (pounds and inches) or Metric units (metres and kilograms). Here is the code I have for this part, so far:

'Here's where I attempt the BMI calculations. Wish me luck.
Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
lblBMIHeader.Visible = True
lblBMI.Visible = True
'Here are the declarations. I'm seriously hoping I got this part right.
Dim decUS As Decimal
Dim decMetric As Decimal
Dim decHeight As Decimal
Dim decWeight As Decimal
If radUS.Checked = True Then 'The process that uses pounds and inches
decHeight = Convert.ToDecimal(txtHeight.Text)
decWeight = Convert.ToDecimal(txtWeight.Text)
If decHeight > 0 And decWeight > 0 Then
decUS = (decWeight / decHeight ^ 2) * 703
lblBMI.Text = decUS.ToString("00.0")
ElseIf (decHeight <= 0 And decWeight <= 0) Or (decHeight <= 0 Or decWeight <= 0) Then
MsgBox("Please try again. Only numbers greater than 0 should be in this field.", 16, "Entry Invalid")
txtHeight.Text = ""
txtWeight.Text = ""
txtHeight.Focus()
txtWeight.Focus()
Else
MsgBox("Please enter a positive number in the text boxes.", 16, "Entry Invalid")
txtHeight.Text = ""
txtWeight.Text = ""
txtHeight.Focus()
txtWeight.Focus()
End If
ElseIf radMetric.Checked = True Then 'The process that uses kilograms and metres
decHeight = Convert.ToDecimal(txtHeight.Text)
decWeight = Convert.ToDecimal(txtWeight.Text)
If decHeight > 0 And decWeight > 0 Then
decMetric = decWeight / decHeight ^ 2
lblBMI.Text = decMetric.ToString("00.0")
ElseIf (decHeight <= 0 And decWeight <= 0) Or (decHeight <= 0 Or decWeight <= 0) Then
MsgBox("Please enter a number greater than 0", 16, "Entry Invalid")
txtHeight.Text = ""
txtWeight.Text = ""
txtHeight.Focus()
txtWeight.Focus()
Else
MsgBox("Please enter a positive number in the text boxes.", 16, "Entry Invalid")
txtHeight.Text = ""
txtWeight.Text = ""
txtHeight.Focus()
txtWeight.Focus()
End If
End If
End Sub

And here is what the interface looks like in the designer (the above code is tied to the 'Calculate' button):

I have more to do with this program before it's completed but I'm stumped with how to calculate the values entered into the textbox objects. I thought that linking the values with 'And' statements would be the best way to solve the problem but it didn't work. I'm not sure how to proceed from here and was wondering if anyone here had any ideas?

Update: I added an IsNumeric statement and defined the values globally and set them equal to 0. I managed to stop it from accepting numbers less than or equal to 0. I tried entering non-numeric characters only for it to throw out an exception. This happened when either the "Imperial (US)" or the "Metric" radio buttons were selected. Here is the updated code beginning with the declarations:

Dim decHeight As Decimal = 0
Dim decWeight As Decimal = 0
Dim decUS As Decimal = 0
Dim decMetric As Decimal = 0

I decided to keep the decUS and decMetric decimal values in the code for now. These are closer to the beginning of the code. The updated version of the relevant code looks like this:

Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
        lblBMIHeader.Visible = True
        lblBMI.Visible = True
        If radUS.Checked = True Then 'The process that uses pounds and inches
            decHeight = Convert.ToDecimal(txtHeight.Text)
            decWeight = Convert.ToDecimal(txtWeight.Text)
            'The "IsNumeric" statements should keep any non-numeric characters from becoming a problem.
            'The rule for both Metric and Imperial measurements is that we want numbers greater than 0.
            'Anything else should spit out an error message.
            If IsNumeric(txtHeight.Text And txtWeight.Text) Then
                If decHeight > 0 And decWeight > 0 Then
                    decUS = (decWeight / decHeight ^ 2) * 703
                    lblBMI.Text = decUS.ToString("00.0")
                Else
                    MsgBox("Please try again. Only numbers greater than 0 should be in this field.", 16, "Entry Invalid")
                    txtHeight.Text = ""
                    txtWeight.Text = ""
                    txtHeight.Focus()
                    txtWeight.Focus()
                End If
            Else
                MsgBox("Please enter a positive number in the text boxes.", 16, "Entry Invalid")
                txtHeight.Text = ""
                txtWeight.Text = ""
                txtHeight.Focus()
                txtWeight.Focus()
            End If
        ElseIf radMetric.Checked = True Then 'The process that uses kilograms and metres
            decHeight = Convert.ToDecimal(txtHeight.Text)
            decWeight = Convert.ToDecimal(txtWeight.Text)
            If IsNumeric(txtHeight.Text And txtWeight.Text) Then
                If decHeight > 0 And decWeight > 0 Then
                    decMetric = decWeight / decHeight ^ 2
                    lblBMI.Text = decMetric.ToString("00.0")
                ElseIf (decHeight <= 0 And decWeight <= 0) Or (decHeight <= 0 Or decWeight <= 0) Then
                    MsgBox("Please enter a number greater than 0", 16, "Entry Invalid")
                    txtHeight.Text = ""
                    txtWeight.Text = ""
                    txtHeight.Focus()
                    txtWeight.Focus()
                End If
            Else
                MsgBox("Please enter a positive number in the text boxes.", 16, "Entry Invalid")
                txtHeight.Text = ""
                txtWeight.Text = ""
                txtHeight.Focus()
                txtWeight.Focus()
            End If
        End If
    End Sub

I'm a bit closer but I suspect I'm going to need to focus my attention elsewhere. This assignment requires that I add more things to the program (including a loop and a pictureBox object with 2 pictures in it). Wish me luck.

Update 2: I solved the problem I was running into where entering a non-numeric character, or nothing at all for that matter, would spit out an exception. The problem I ran into is that I had 1 IsNumeric handling input from both textboxes. I also moved the Convert statements below the Isnumeric statements. The new code looks like this:

'Here's where I attempt the BMI calculations. Wish me luck.
    Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
        lblBMIHeader.Visible = True
        lblBMI.Visible = True
        If radUS.Checked = True Then 'The process that uses pounds and inches
            'The "IsNumeric" statements should keep any non-numeric characters from becoming a problem.
            'The rule for both Metric and Imperial measurements is that we want numbers greater than 0.
            'Anything else should spit out an error message.
            If IsNumeric(txtHeight.Text) And IsNumeric(txtWeight.Text) Then
                decHeight = Convert.ToDecimal(txtHeight.Text)
                decWeight = Convert.ToDecimal(txtWeight.Text)
                If decHeight > 0 And decWeight > 0 Then
                Else
                    MsgBox("Please try again. Only numbers greater than 0 should be in this field.", 16, "Entry Invalid")
                    txtHeight.Text = ""
                    txtWeight.Text = ""
                    txtHeight.Focus()
                    txtWeight.Focus()
                End If
                decUS = (decWeight / decHeight ^ 2) * 703
                lblBMI.Text = decUS.ToString("00.0")
            Else
                MsgBox("Please enter a positive number in the text boxes.", 16, "Entry Invalid")
                txtHeight.Text = ""
                txtWeight.Text = ""
                txtHeight.Focus()
                txtWeight.Focus()
            End If

        ElseIf radMetric.Checked = True Then 'The process that uses kilograms and metres

            If IsNumeric(txtHeight.Text) And IsNumeric(txtWeight.Text) Then
                decHeight = Convert.ToDecimal(txtHeight.Text)
                decWeight = Convert.ToDecimal(txtWeight.Text)
                If decHeight > 0 And decWeight > 0 Then
                ElseIf (decHeight <= 0 And decWeight <= 0) Or (decHeight <= 0 Or decWeight <= 0) Then
                    MsgBox("Please enter a number greater than 0", 16, "Entry Invalid")
                    txtHeight.Text = ""
                    txtWeight.Text = ""
                    txtHeight.Focus()
                    txtWeight.Focus()
                End If
                decMetric = decWeight / decHeight ^ 2
                lblBMI.Text = decMetric.ToString("00.0")
            Else
                MsgBox("Please enter a positive number in the text boxes.", 16, "Entry Invalid")
                txtHeight.Text = ""
                txtWeight.Text = ""
                txtHeight.Focus()
                txtWeight.Focus()
            End If
        End If

    End Sub

Now I have to come up with a way to throw some pieces of garbage code into my program before noon tomorrow (and by "garbage code" I mean code that has garbage pieces in it that don't do anything). Wish me luck.

6 Upvotes

7 comments sorted by

1

u/Mr_C_Baxter VB.Net Master Oct 14 '20

Hey man. First of all, thanks for a nicely formated question. That is getting rare.

I think one of your problems is that you are trying to much in a simple function so you trick yourself with all the stuff. I would give you the advice to break the problem down into smaller pieces. And the best way to achieve this in code is via functions, they help you to visualize the stuff which needs to be done. So lets build a small example just to see it structured:

Public Class Form1

Dim CurrentHeight As Decimal = 0
Dim CurrentWeight As Decimal = 0
Dim BMI As Decimal = 0

Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click

    'First Update the GUI
    UpdateGUI()

    'Load input in our global variables
    LoadInput()

    'Whats does the user want to do?
    Dim Action As String = GetUserAction()

    'do different calculations for different actions
    Select Case Action
        Case "Metric"
            'input is in metres and kg -> no conversion needed
            BMI = CurrentWeight / CurrentHeight ^ 2
        Case "Us"
            'input is in metres and kg -> convert to pounds and inches
            Dim Pounds As Decimal = CurrentWeight * 2.2
            Dim Inches As Decimal = CurrentHeight * 39.37
            BMI = (Pounds * 703) / Inches ^ 2

    End Select

    MsgBox(BMI)

End Sub

Private Sub UpdateGUI()

    lblBMIHeader.Visible = True
    lblBMI.Visible = True

End Sub

Private Sub LoadInput()

    CurrentHeight = Convert.ToDecimal(txtHeight.Text)
    CurrentWeight = Convert.ToDecimal(txtWeight.Text)

End Sub

Private Function GetUserAction() As String

    If radUS.Checked = True Then Return "Us"
    If radMetric.Checked = True Then Return "Metric"

    Return ""

End Function

End Class

I think this should contain all you need to adapt your example, try it out and hit me up if it does not help.

2

u/MelloYelloSurge VB.Net Beginner Oct 21 '20

It's an interesting idea, but it falls outside the scope of my assignment. The assignment I was working on required the use of a nested if statement and I wanted to make sure to assign the values that come up on the screen based on the radio button the user selected. Also, while the code above won't show it, some pieces of the UI were different based on the radio button selected by the user. That said, I thank you for the suggestion in your post. I appreciate it more than you know.

2

u/Mr_C_Baxter VB.Net Master Oct 21 '20

Ah okay, I did not assume the nested If is mandatory. I hope you still got the solution, even if this is one of the bad assignments from some lazy prof / teacher

2

u/MelloYelloSurge VB.Net Beginner Oct 21 '20

I finally got it...at the expense of my sanity. If that weren't bad enough, I have to throw in some garbage code in order to get closer to an A on this assignment. I'm not looking forward to bloated code, but here we are. If I take that class again, I'll need to make a benefit payment calculator so that I have something that uses loops without garbage code. Now if you'll excuse me, this girl needs her rest. Thank you again for the suggestion in your original post. You deserve a drink for your hard work.

2

u/Mr_C_Baxter VB.Net Master Oct 21 '20

hehe, thank you very much and enjoy your rest. If you need further help with programming you can always send me a dm. And I just want to confirm that you are on the right track in regards to your mindset. But don't take those assignments seriously, 90% of the time they are bullshit like this. Stupid converters or this other calculator you mention. I usually start with new students with something they at least have a benefit of in the long run. Last time it was a "Music Library". Basically find MP3s on the computer and give some options like tagging, sorting, displaying album art and stuff.

1

u/andrewsmd87 Web Specialist Oct 14 '20

I would put in break points and step through your code. Assuming your ifs are set up correctly you're doing the math on lines 46 or 84, and then setting the label, so I'm guessing it's never getting into the portion of the if you think it is.

Also

decHeight = Convert.ToDecimal(txtHeight.Text)

decWeight = Convert.ToDecimal(txtWeight.Text)

Will throw an error if you type something like asdf in one of those text boxes. It'd be a good idea to use IsNumeric to check they're numbers first.

1

u/MelloYelloSurge VB.Net Beginner Oct 21 '20

Thank you for pointing out the IsNumeric issue. I owe you a drink.