• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2206
  • Last Modified:

Calculate average with array and class

I am new and am having difficulties.  I have a text box a user can enter up to 10 numbers, a button to enter the numbers and another to average the numbers with the results in a 2nd text box. Now an easy way to do this would be as follows.
 
Public Class frmAverage
  Dim count As Integer = 0
  Dim total As Integer = 0

  Private Sub btnRecordNumber_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRecordNumber.Click
    'Add the numbers to the total
    total += CInt(txtNumber.Text)
    count += 1
    txtNumber.Clear()
    txtNumber.Focus()
  End Sub

  Private Sub btnCalculateAverage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculateAverage.Click
    'Average the numbers to the total
    txtAverage.Text = CStr(total / count)
  End Sub
End Class         'frmAverage

However, I am required to use a class named Statistics and have an AddNumber method that stores numbers into an array one at a time. The class should have a Count property that keeps track of the number of numbers stored and a method called Average that returns the average of the numbers.  Therefore, I have come up with this but I think I am getting really lost in what I am doing.  I think I just need someone to point me in the correct direction.  Any advice would be appreciated.  

Public Class frmAverage
  Dim numbr(50) As Statistics
  Dim count As Double
  Dim lastNumAdded As Double  'position in array the last number addes

  Private Sub btnRecordNumber_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRecordNumber.Click
    'Add the numbers and count
    number += CInt(txtNumber.Text)
    count += 1
    txtNumber.Clear()
    txtNumber.Focus()

  End Sub

  Private Sub btnCalculateAverage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculateAverage.Click
    'Average the numbers
    'num.Count(CDbl(txtNumber.Text))
    txtAverage.Text = number / 2
    txtNumber.Clear()
    txtNumber.Focus()
  End Sub
End Class         'frmAverage

Class Statistics

  Private m_addNumber As String
  Public Property number() As String
  Public WriteOnly Property addNumber() As Double
    Set(ByVal value As Double)
      m_addNumber = number
    End Set
  End Property

End Class
0
voyager1845
Asked:
voyager1845
2 Solutions
 
Todd GerbertIT ConsultantCommented:
Sounds like they want you to create a class named Statistics and use that to do the heavy lifting. Do you any code now in the Statistics class?

This way your form's code will look a little like:
Dim stats As New Statistics()

Private Sub btnRecordNumber_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRecordNumber.Click
    Dim n As Integer
    If Int32.TryParse(txtNumber.Text, n)
        stats.AddNumber(n)
    Else
        MessageBox.Show("You did not enter a number.")
    End If
End Sub

Private Sub btnCalculateAverage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculateAverage.Click
    txtAverage.Text = stats.Average.ToString();
End Sub

Open in new window

0
 
Robberbaron (robr)Commented:
i have fleshed out the class a bit more. You should have an initializing block as well. see the New() method.

http://msdn.microsoft.com/en-us/library/ms973814.aspx#creatingclasses_topic3

you dont need the public keyword as all properties are public.
Class Statistics

  Private m_currenttotal As double  '<<<<< this counts all the added numbers
  Private m_currentcount as long    'counts how many numbers have been added
  
  
  WriteOnly Property addNumber() As Double
    Set(ByVal value As Double)
      m_currenttotal +=  value   'build the total
      m_currentcount += 1  'increment the counter
    End Set
  End Property
  
  ReadOnly Property Average() as double
       Get
           Return currenttotal / currentcount
       End Get
  End Property

End Class

Open in new window

0
 
Jeff CertainCommented:
A few things.

AddNumber should be a method (sub or function) not a property.

If you can reason with your teacher/prof, use a List(Of Integer) instead of an array. It's type-safe and gives you a performance benefit since there's no boxing/unboxing. As an added benefit, you get Add() for free, and since it implements IEnumerable(Of T) there's an Average extension method baked in. (I don't know of any professionals that use arrays; generic collections, introduced in .NET 2.0, are far superior).

Dim numbr(50) As Statistics.... this should be "Private statistics As New Statistics".  It doesn't need to be an array of Statistics -- the Statistics class will contain the array, and manage it through the AddNumber method. Which, btw, raises another reason generic collections such as List are nice -- you don't have to manage the allocation of memory based on the size.

0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Robberbaron (robr)Commented:
Chaosian is correct. AddNumber should be a method.
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
0
 
ArkCommented:
Though this is 'Classic' area, IMHO, 'Net' way should be:
Public Class StatList
    Inherits List(Of Double)

    Private m_Sum As Double

    Public Overloads Sub Add(ByVal value As Double)
        MyBase.Add(value)
        m_Sum += value
    End Sub
    Public Overloads Sub AddRange(ByVal values() As Double)
        MyBase.AddRange(values)
        For i As Integer = 0 To values.Count - 1
            m_Sum += values(i)
        Next
    End Sub
    Public Overloads Sub Clear()
        MyBase.Clear()
        m_Sum = 0
    End Sub
    Public ReadOnly Property Average() As Double
        Get
            If MyBase.Count = 0 Then Return 0
            Return m_Sum / MyBase.Count
        End Get
    End Property
End Class

Open in new window


Now you can use all benefits of List(of double)
Dim StList As New StatList
'AddRange allow add an array at once
StList.AddRange(New Double() {1.1, 2.22, 3.333, 4.4444, 5.55555})
MsgBox(StList.Average)
'Build in
MsgBox(StList.Min)
MsgBox(StList.Max)
'As well as Find,BinarySearch, contains etc,etc
0
 
voyager1845Author Commented:
Chaosian is correct. AddNumber should be a method. I didn't want to do a bunch of copy past as this is for a class.  I needed to learn it.  But I did use some of the suggestions given to me.  Here is the final code I ended up with.  Thank you tgerbert for the code TryParse method.  Being new I haven’t seen it before so I went off and learned what it was all about.  Interesting, if a input is not correct it will not error out when using non numeric variables.  Using it you can check for invalid inputs.  Thank you all for the help and not getting on to me being a student and asking for help.  One more week to go.    

Public Class frmAverage
  Private Stats As New Statistics


  Private Sub btnRecord_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRecord.Click
    Dim TheNumberEntered As Decimal
    If Decimal.TryParse(txtNumber.Text, TheNumberEntered) Then
      Stats.AddNumber(CInt(TheNumberEntered))
      txtNumber.Text = Nothing
      txtNumber.Focus()

    Else
      MessageBox.Show("Invalid Grade Entered")
    End If
  End Sub

  Private Sub btnCalculateAverage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculateAverage.Click
    txtAnswer.Text = CStr(Stats.Average)


  End Sub
End Class
Class Statistics
  Private m_numbers(49) As Integer

  Private m_count As Integer   'Count of numbers entered into array

  Sub AddNumber(ByVal number As Integer)
    'Adds a number to the statistics
    m_count += 1
    m_numbers(m_count) = number
  End Sub

  Public ReadOnly Property Count() As Integer
    'Counter of numbers stored
    Get
      Return m_count
    End Get
  End Property

  Function Average() As Double
    'Computes the average
    Dim sum As Integer = 0
    For i As Integer = 1 To m_count
      sum += m_numbers(i)
    Next
    Return sum / m_count
  End Function

End Class    'Statistics

Open in new window

0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now