views:

662

answers:

2

I am trying to create a DisplayAverage sub procedure that accepts 3 integer numbers as parameters. This procedure should find the average of these 3 numbers and display the numbers along with their average in the list box. I know im doing something wrong here I just cant figure out what. Thanks in advanced.

Private Sub btnAverage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAverage.Click
    Dim a As Integer = CInt(txtone.Text)
    Dim b As Integer = CInt(txtTwo.Text)
    Dim c As Integer = CInt(txtThree.Text)
    Dim average As Double
    average = (a + b + c) / 3

    lstOutput.Items.Add(average.ToString())





End Sub

Sub DisplayMyName()
    lstOutput.Items.Add("David Whitney")
End Sub

Sub DisplayAverage()
    Dim a As Integer = CInt(txtone.Text)
    Dim b As Integer = CInt(txtTwo.Text)
    Dim c As Integer = CInt(txtThree.Text)
    Dim average As Double
    average = (a + b + c) / 3

    lstOutput.Items.Add("The average of " & a & " and " _
            & b & " and " & c & " is " & average)


End Sub

Private Sub btnAve_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAve.Click
    lstOutput.Items.Clear()
    DisplayMyName()

    Dim a As Integer = CInt(txtone.Text)
    Dim b As Integer = CInt(txtTwo.Text)
    Dim c As Integer = CInt(txtThree.Text)
    Dim average As Double
    average = (a + b + c) / 3

    lstOutput.Items.Add(average.ToString())

    DisplayAverage()



End Sub

End Class

+1  A: 

You have the code to do the average written out several times. All you really need to do is this:

Private Sub btnAve_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAve.Click
    lstOutput.Items.Clear()
    lstOutput.Items.Add("David Whitney")
    Dim a,b,c As Float
    Try
        a = Convert.ToSingle(txtone.Text)
        b = Convert.ToSingle(txtTwo.Text)
        c = Convert.ToSingle(txtThree.Text)
    Catch ex As FormatException
        MessageBox.Show("Please enter a valid number for a, b, and c.", "Error")
        Exit Sub
    End Try

    Dim average As Double = (a + b + c) / 3

    lstOutput.Items.Add("The average of " & a & " and " _
        & b & " and " & c & " is " & average)
End Sub
Chris Thompson
A: 

I agree Chris that you need the code in one place, but I would not have it in the button click event. Place it in its own routine, called average or similar.

And, there is a better way to average numbers, if you are using .NET Framework 3.5 ... LINQ. You can find the basics here: http://tinyurl.com/bd2zcq

The benefit of the LINQ method is you can average as many numbers as you desire, so the algorithm has great reuse. Perhaps a helper class?

Gregory A Beamer
I agree with that, I was trying to keep it simple for what looks to be a homework assignment type project.
Chris Thompson
It's a bit like when code samples are simplified and then the slightly wrong simplification makes it into thousands of apps ;)
Mitch Wheat