VB Array Error Grade Book Assignment - arrays

My problem is when I input scores for four tests: 1 2 3 3, it calculates total and average everything is working great, but if I put scores for tests bigger than 3, which is bigger than my array it gives me error in this function
Public Function TotalScore(studentScore() As Integer, intTotalScore As Integer) As Integer
For Each i As Integer In studentScore
intTotalScore += studentScore(i)
Next
Return intTotalScore
End Function
the error message is that index is out of range array.
I am sorry I don't know how to explain it better if you need additional code or some more details I will be more than happy to provide. Thank you for your time
Public g_intTotalScore As Integer 'total score
Public g_decAverageScore As Decimal 'average score
Public g_strLetterScore As String
Public Const intMAX_SUBSCRIPT_STUDENTS_NAMES As Integer = 4 'max subscript for students names
Public Const intMAX_SUBSCRIPT_SCORE As Integer = 3 'max subscript for student numeric scores on 4 test
Public strStudentsNames(intMAX_SUBSCRIPT_STUDENTS_NAMES) As String 'array that holds students names
Public strLetterGrades() As String = {"A", "B", "C", "D", "F"} 'array that hold letter grades
Public intStudent1(intMAX_SUBSCRIPT_SCORE) As Integer 'hold test scores for student1
I create function that accepts two parameters to calculate total score of 4 tests
Public Function TotalScore(studentScore() As Integer, intTotalScore As Integer) As Integer
For Each i As Integer In studentScore
intTotalScore += studentScore(i)
Next
Return intTotalScore
End Function
Here is input for Student Name and than 4 test scores
Do While intCount < strStudentsNames.Length
'input data for student number1
If intCount = 0 Then
intCounter = 0
strStudentsNames(intCount) = InputBox("Enter Student Name number" & intCount + 1, "Enter Data")
Do While intCounter < intStudent1.Length
intStudent1(intCounter) = CInt(InputBox("Student Name: " & strStudentsNames(intCount) & vbCrLf &
"Enter Score for test number " & intCounter + 1, "Enter Data"))
intCounter += 1
Loop
End If
intCount += 1
Loop
here is display data to list
'student1: calculate total , avaerage score, display average score, reset total score
g_intTotalScore = TotalScore(intStudent1, g_intTotalScore)
g_decAverageScore = Average(g_decAverageScore)
lstOutPut.Items.Add("Student Name: " & strStudentsNames(0) & " => The average score is: " & g_decAverageScore.ToString & " => Grade: ")
g_intTotalScore = 0

The error means that you are trying to get something from the array index that doesn't exists in the array. For example the array has 10 elements from 0 - 9 index and your calling the index number 11.
Try to use the for each like this:
For Each i As Integer In studentScore
intTotalScore += i
Next

Related

Compare strings to identify duplicates

I have to write an isDup function to compare two tweets based on their similar word counts to determine if the tweets are duplicate, based on a decimal threshold chosen (0-1).
My process is to write a sub with two hardcoded tweets my prof has provided (just to get an understanding before converting to a function). I encountered a run time error 5.
Option Explicit
Sub isDup()
Dim tweet1 As String
Dim tweet2 As String
Dim threshold As Double
threshold = 0.7
tweet1 = "Hours of planning can save weeks of coding"
tweet2 = "Weeks of programming can save you hours of planning"
Dim tweet1Split() As String
tweet1Split = Split(tweet1, " ")
Dim tweet2Split() As String
tweet2Split = Split(tweet2, " ")
Dim i As Integer
Dim j As Integer
Dim sameCount As Integer
'my thought process below was to compare strings i and j to see if equal, and if true add 1 to sameCount,
'but the If StrComp line is where the error is
For i = LBound(tweet1Split) To UBound(tweet1Split) Step 1
For j = LBound(tweet2Split) To UBound(tweet2Split) Step 1
If StrComp(i, j, vbDatabaseCompare) = 0 Then
sameCount = sameCount + 1
Exit For
End If
Next j
Next i
End Sub
'here i wanted to get a total count of the first tweet to compare, the duplicate tweet is true based on the number of
'similar words
Function totalWords(tweet1 As String) As Integer
totalWords = 0
Dim stringLength As Integer
Dim currentCharacter As Integer
stringLength = Len(tweet1)
For currentCharacter = 1 To stringLength
If (Mid(tweet1, currentCharacter, 1)) = " " Then
totalWords = totalWords + 1
End If
Next currentCharacter
End Function
'this is where i compute an "isDup score" based on similar words compared to total words in tweet1, in this
'example the threshold was stated above at 0.7
Dim score As Double
score = sameCount / totalWords
If score > threshold Then
MsgBox "isDup Score: " & score & " ...This is a duplicate"
Else
MsgBox "isDup Score: " & score & " ...This is not a duplicate"
End If
End Sub
First issue:
i and j are just indexes. You want to compare the string that your index relates to so:
If StrComp(tweet1Split(i), tweet2Split(j), vbDatabaseCompare) = 0 Then
Second issue:
As noted in Microsoft documentation for StrComp, vbDatabaseCompare is reserved for Access, which you are not using, hence the source of your second error. You need to switch to a different comparison

How to return the rank of each double in an array when there are duplicate values?

If my input array is (10,10,20,20,30,30,40,40,50,50) I would like a simple piece of code that would return (1,2,3,4,5,6,7,8,9,10). I am trying to implement an ABC classification and I am currently using this code:
For i = 1 To noA 'noA number of items should be classified as "A"
'return the item number with the i'th largest number in arrTembABC
intTemp = Application.Match(WorksheetFunction.Large(arrTempABC, i), arrTempABC, True)
'assign the category "A" to 'intTemp' item number
SKUinfo(intTemp, 12) = "A"
Next i
'some printing code
The problem with the above code is that when there are duplicate values, it always returns the position of the first instance. Any other item number with the same value does not get assigned a category.
So for the array discussed above (see "avg value") the code only classifies the first instance of each duplicate value, and the rest are blank (see "ABC_CategCry")
I resorted to sorting the array that holds the values while holding their positions in a separate array. I post the entire sub below that does an ABC classification based either on volume or value (=avg volume*cost). I tried to comment in an informative way but appreciate any questions for clarification or comments on how to improve clarity.
Sub ABCclass(ByRef swtcABCclass As Integer, ByRef prcA As Double, ByRef prcB As Double, _
ByRef prcC As Double)
Dim arrTempABC() As Double, i As Integer, j As Integer, intTemp As Integer, tempABC As Double
Dim noA As Integer, noB As Integer, noC As Integer, arrTempTSno() As Integer
ReDim arrTempABC(1 To tsTot)
ReDim arrTempTSno(1 To tsTot)
'populate the array that holds the values by which we classify the SKUs
If swtcABCclass = 1 Then 'ABC based on volume*value
For i = 1 To tsTot
arrTempABC(i) = SKUinfo(i, 11) * SKUinfo(i, 5) 'average monthly volume*value (cost)
arrTempTSno(i) = i 'just hold the position (ascending number of the timeseries/SKU)
Next i
ElseIf swtcABCclass = 2 Then 'ABC based on volume
For i = 1 To tsTot
arrTempABC(i) = SKUinfo(i, 11) ' average monthly volume
arrTempTSno(i) = i
Next i
End If
'find the limits of each class (in terms of percentages of SKUbase)
noA = WorksheetFunction.RoundDown(tsTot * prcA, 0) 'first prcA% of the tsTot (number of timeseries or SKUs) are in class A
noB = noA + WorksheetFunction.RoundDown(tsTot * prcB, 0)
noC = tsTot
'sort arrTempABC while saving the positions in a seperate array
For i = 2 To tsTot
tempABC = arrTempABC(i)
intTemp = arrTempTSno(i)
For j = i - 1 To 1 Step -1
If arrTempABC(j) >= tempABC Then Exit For
arrTempABC(j + 1) = arrTempABC(j)
arrTempTSno(j + 1) = arrTempTSno(j)
Next
arrTempABC(j + 1) = tempABC
arrTempTSno(j + 1) = intTemp
Next
'now that i have the sorted positions, i can just assign the categories
For i = 1 To noA 'noa number of items should be classified as "A"
SKUinfo(arrTempTSno(i), 12) = "A"
Next i
For i = noA + 1 To noB 'nob - (noa +1) number of items should be classified as "B"
SKUinfo(arrTempTSno(i), 12) = "B"
Next i
For i = noB + 1 To noC 'noc - (nob +1) number of items should be classified as "C"
SKUinfo(arrTempTSno(i), 12) = "C"
Next i
End Sub

Assigning a value to array in visual basic

This visual basic program prompts the user
to interactively enter 4 integer values, which the program
stores in an array. It should then find the minimum and maximum
values stored in the array, as well as the average of the 4 values.
The code is
Option Explicit On
Option Strict On
Module BattingAverage
Sub Main()
Const MAX_AVERAGES AS Integer = 3
Dim Averages(MAX_AVERAGES -1) as Double
Dim LoopIndex As Integer
Dim BattingAverage As Double
Dim BattingString As String
Dim Min As Double
Dim Max As Double
Dim Total As Double
Dim Average As Double
For LoopIndex = 0 To MAX_AVERAGES - 1
BattingString = InputBox$("Enter a batting average: ")
BattingAverage = Convert.ToDouble(BattingString)
'Assigning a value to Array
Averages(LoopIndex) += BattingAverage
Next LoopIndex
Min = Averages(0)
Max = Averages(0)
Total = Averages(0)
For LoopIndex = 1 To Averages.length -1
If Averages(LoopIndex) < Min then
Min = Averages(LoopIndex)
Else If Averages(LoopIndex) > Max then
Max = Averages(LoopIndex)
end if
Total += Averages(LoopIndex)
'
Next LoopIndex
Average = Total / MAX_AVERAGES
System.Console.WriteLine("Batting Averages : " & Averages(LoopIndex))
System.Console.WriteLine("Maximum value : " &Max)
System.Console.WriteLine("Minimum value : " &Min)
System.Console.WriteLine("Average : " &Average)
End Sub
End Module
I ran the code but it throws this indexoutofbound exception
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
at BattingAverage.Main()
I am not sure how to fix this code. I also think that my code(Averages(LoopIndex) += BattingAverage) to assign a value to array is not right. please help
There are a couple things wrong here. First off if you want to take 4 values, you need to change MAX_AVERAGES = 4. The error is coming from this line
System.Console.WriteLine("Batting Averages : " & Averages(LoopIndex))
because here LoopIndex has been incremented to 3, which is out of bounds of an array of size 3. Averages(2) is the last index. You should change the line to
Console.WriteLine("Batting Averages: ")
For i = 0 To Averages.Length - 1
Console.WriteLine(Averages(i).ToString)
Next
obl is correct on the above part with array size and was close on the print portion.
Your Original :
System.Console.WriteLine("Batting Averages : " & Averages(LoopIndex))
System.Console.WriteLine("Maximum value : " &Max)
System.Console.WriteLine("Minimum value : " &Min)
System.Console.WriteLine("Average : " &Average)
End Sub
How it should read:
For LoopIndex = 0 To 3
System.Console.WriteLine("Batting Averages : " &Averages(LoopIndex))
Next
System.Console.WriteLine("Maximum value : " &Max)
System.Console.WriteLine("Minimum value : " &Min)
System.Console.WriteLine("Average : " &Average)
End Sub
The code was not able to execute based on how large your array was as your code reads that it should print all values in the array, if your array was only one value in size, it would have been able to print. So, you need a For LoopIndex = "bounds of the array" for this to work.

Sort array numerically, with strings and integers

i have an array which has a name and a score next to it, i need it to be sorted high to low. i already have it sorted alphabetically.
Dim reply3 As String
Dim name As String
Dim score As Integer = 0
Dim classnum As Integer
Dim filePath As String
Dim reply As Integer
Dim reply2 As Integer
Dim strline As String
Dim array() As String
Sub Main()
Console.Title = "Math Test"
Console.WriteLine("Do you want to start the test or view previous results? Press 1 for test, 2 for results")
reply = Console.ReadLine
If reply > 2 Then
MsgBox("Invalid Reply Press Ok to end")
End
End If
If reply = 2 Then
Console.WriteLine("What class do you want to see the results of? 1, 2, or 3?")
reply2 = Console.ReadLine()
End If
If reply2 > 3 Then
MsgBox("Invalid Reply Press Ok to exit")
End
End If
Select Case reply2
Case 1
Dim results1 As String = File.ReadAllText("Z:\scores class 1.txt")
array = Split(results1, "-")
For i As Integer = 0 To array.Length - 1
Console.WriteLine(array(i))
Next
Console.WriteLine("Would you like these to be sorted? Press 1 for yes, 2 for no")
If Console.ReadLine = 1 Then
System.Array.Sort(array)
For i As Integer = 0 To array.Length - 1
Console.WriteLine(array(i))
Next
ElseIf Console.ReadLine = 2 Then
End
End If
Console.ReadLine()
Case 2
Dim results1 As String = File.ReadAllText("Z:\scores class 2.txt")
array = Split(results1, "-")
For i As Integer = 0 To array.Length - 1
Console.WriteLine(array(i))
Next
Console.WriteLine("Would you like these to be sorted? Press 1 for yes, 2 for no")
If Console.ReadLine = 1 Then
System.Array.Sort(array)
For i As Integer = 0 To array.Length - 1
Console.WriteLine(array(i))
Next
ElseIf Console.ReadLine = 2 Then
End
End If
Console.ReadLine()
Case 3
Dim results1 As String = File.ReadAllText("Z:\scores class 3.txt")
array = Split(results1, "-")
For i As Integer = 0 To array.Length - 1
Console.WriteLine(array(i))
Next
Console.WriteLine("Would you like these to be sorted? Press 1 for yes, 2 for no")
If Console.ReadLine = 1 Then
System.Array.Sort(array)
For i As Integer = 0 To array.Length - 1
Console.WriteLine(array(i))
Next
ElseIf Console.ReadLine = 2 Then
End
End If
Console.ReadLine()
End Select
If reply = 1 Then
Console.WriteLine("What is your name?")
name = Console.ReadLine
Console.WriteLine("What class are you in, 1, 2 or 3?")
classnum = Console.ReadLine
If classnum < 1 Then
MsgBox("Invalid Class number")
End
ElseIf classnum > 3 Then
MsgBox("Invalid Class number")
End
End If
Console.WriteLine("What is 9+10 ?")
If Console.ReadLine = 19 Then
score += 1
End If
Console.WriteLine("What is 5x10 ?")
If Console.ReadLine = 50 Then
score += 1
End If
Console.WriteLine("What is 122÷2 ?")
If Console.ReadLine = 61 Then
score += 1
End If
Console.WriteLine("What is 424 + 10 ?")
If Console.ReadLine = 434 Then
score += 1
End If
Console.WriteLine("What is 234 x 3 ?")
If Console.ReadLine = 702 Then
score += 1
End If
Console.WriteLine("What is 10 x 10 ?")
If Console.ReadLine = 100 Then
score += 1
End If
Console.WriteLine("What is 12 x 64 ?")
If Console.ReadLine = 768 Then
score += 1
End If
Console.WriteLine("What is the value of N in this equation? 2n+6=10?")
If Console.ReadLine = 4 Then
score += 1
End If
Console.WriteLine("What is 9 x 73 ?")
If Console.ReadLine = 657 Then
score += 1
End If
Console.WriteLine("What is 1 + 1 ?")
If Console.ReadLine = 2 Then
score += 1
End If
MsgBox("Your score was " & score & " Click ok to finish.")
Dim output1 As String = name & " " & score & "-"
Select Case classnum
Case 1
filePath = System.IO.Path.Combine(
My.Computer.FileSystem.SpecialDirectories.MyDocuments, "scores class 1.txt")
My.Computer.FileSystem.WriteAllText(filePath, output1, True)
Case 2
filePath = System.IO.Path.Combine(
My.Computer.FileSystem.SpecialDirectories.MyDocuments, "scores class 2.txt")
My.Computer.FileSystem.WriteAllText(filePath, output1, True)
Case 3
filePath = System.IO.Path.Combine(
My.Computer.FileSystem.SpecialDirectories.MyDocuments, "scores class 3.txt")
My.Computer.FileSystem.WriteAllText(filePath, output1, True)
End Select
End If
End Sub
I need the array called array to be sorted numerically. i will add the option for the user to choose if he/she wants further sorting after it has been done alphabetically.
Strings are not numbers. They are text.
In string format, they are simply characters (numerals) and they do not and will not sort numerically:
Dim myVals As String() = {"5", "07", "178", "9", "899", "42", "3"}
' add two of the "numbers"
Console.WriteLine("{0} + {1} = {2}", myVals(0),
myVals(1), (myVals(0) + myVals(1)))
Array.Sort(myVals)
Array.Reverse(myVals)
For Each s As String In myVals
Console.Write("{0} ", s)
Next
Output:
5 + 07 = 507
9 899 5 42 3 178 07
The values do not add as expected, because they are not numbers. Instead, the code simply concatenates (glues together) two bits of string. The array contents sort as characters also. When sorting, "9" will always be seen as larger than the others.
This applies to dates stored as strings as well. "9/16/1914" will always evaluate larger/later than "12/1/2015".
Why
Because as text, the lexicographical or alphabetical order used (0,1,2,3,4,5,6,7,8,9).
Stored as string, numbers loose their numeric value (until converted). "9" sorts higher than "899" because "9" is higher than "899". The same way that "Able" and "Baker" will sort based on "A" and "B". The "07" sorts lowest because of the zed. The numerical value is ignored because they are strings (text).
The same is true for string "dates" - they are not dates and have no date value. Your brain interprets them as dates based on the pattern; to the computer, they remain text and "9/16/yyyy" will evaluate larger than "12/1/yyyy".
Sort array numerically, with strings and integers
We now know that there are no integers in string arrays, just numerals. But also, if you have 2 pieces of data, you need to store them separately if you want to use them individually. A Class is ideal for this:
Public Class Student
Public Property Name As String
Public Property Score As Integer
Public Sub New()
End Sub
' overload
Public Sub New(n As String, s As Integer)
Name = n
Score = s
End Sub
Public Overrides Function ToString() As String
Return String.Format("{0} ({1})", Name, Score)
End Function
End Class
Notice that the name and score are stored as the correct data type which will allow code to use the Score as a numeric value. Unlike using 2 arrays, the name cannot become detached from the score.
Note also that ToString() allows us to display the data however we want. Just because we want to show the name and score together does not mean we must glue that information together. Sample output:
Charlie (89)
A Students Container
Give up your arrays (and ArrayLists)! It is the 21st Century and we have Typed collections (called Generics):
Private Students As List(of Student) ' declaration
Students is a collection which can only store Student objects, which in turn contains 2 pieces of data. Let's add some:
Students = New List(Of Student) ' create List instance
Dim stud As New Student ' create new student
stud.Name = "Harvey" ' set props
stud.Score = 72 ' 72 is a NUMBER
Students.Add(stud) ' add to collection
' fast way, using the overload, no temp student object needed
Students.Add(New Student("Bob", 67))
Students.Add(New Student("Hoover", 82))
Students.Add(New Student("Ziggy", 97))
...
Students.Add(New Student("Zoey", 89))
Note that we do not have to set the size of the List(of Student) - it grows as it needs to. You can still reference them by element/position: Students(0) is a Student object, and Students(0).Name will be the name of the student in the first slot ("Harvey").
Sorting
Students = Students.OrderByDescending(Function(x) x.Score).ToList()
This creates a new collection in the desired order. To sort matching scores by name:
Students = Students.OrderByDescending(Function(x) x.Score).
ThenBy(Function(q) q.Name).ToList()
' print the contents:
For Each st As Student In Students
Console.WriteLine(st)
Next
The result after adding several matching scores of 89:
Ziggy (97)
Charlie (89)
Echo (89)
Tango (89)
Zoey (89)
Hoover (82)
Harvey (72)
Bob (67)
To track multiple class scores (hinted at in the code), you could add an Id (1,2,3) or Code ("101", "201", "303") to the class to qualify which class, series or set each User-Score belongs. Use an additional .Where() above to get just a subset of the master list.
Finally, rather than storing score sets to individual files, the entire list in its current state can be serialized and saved in 3 or 4 lines of code.
tl;dr
Strings do not contain numbers, nor Dates. They are text.
Don't store individual data elements as one, if you want to use them individually.
What you have is a essentially a multidimensional array containing multiple data types (but in your case, you have concatenated each row into a single string). There isn't a catch-all way to handle this situation, but here are a few methods to consider:
One multidimensional object array:
Dim array(,) As Object = {{"Student1", 95},{"Student2", 87}...}
Two parallel, one dimensional arrays:
Dim names() As String = {"Student1","Student2"...}
Dim scores() As Integer = {95, 87...}
Create a Class or Struct:
Public Class Student
Property name As String
Property score As Integer
End Class
These are all generally better ways of storing your data, but typically put the burden of sorting your data on you. Which leads me to the final option...
Hack together a workaround:
This is essentially what you've already done- concatenated a string with an integer to allow use of the built-in Sort procedure. You can use the same trick to sort by score, but you have to 0-pad your integers if you want them to sort correctly. See code below, but you've been warned: these type of solutions are invariably easier to implement in the short term but grow unwieldy and less useful in the long term, often needing to be replace by one of the "better" solutions above.
Private Sub FlipStrings(ByRef students() As String)
If students Is Nothing Then Exit Sub
For i As Integer = 0 To UBound(students)
Dim parts() As String = Split(students(i))
If parts Is Nothing OrElse UBound(parts) <> 1 Then Continue For
If IsNumeric(parts(0)) Then
students(i) = parts(1) & " " & CInt(parts(0))
ElseIf IsNumeric(parts(1)) Then
Do Until len(parts(1)) = 3 'Assuming max score of 100'
parts(1) = "0" & parts(1)
Loop
students(i) = parts(1) & " " & parts(0)
End If
Next
End Sub
I wrote this so you can still store and display your array exactly as before. Now, to sort by score
FlipStrings(array)
System.Array.Sort(array)
FlipStrings(array)
should give you exactly what you're looking for.

Grade Array Averager troubles

I am currently in an IT curriculum in college. Advance Visual Basic 2010 is a requirement however, I am not a programmer. I have been struggling to find my way through VB but this last assignment has me stumped.I am able to get the first name into the array and the 5 grades for that name . At that point, the loop will continue to ask for the next name and that names 5 grades and so on until the 4th name and grades are entered and then it should display all 4 names and grade averages in the listbox.
Here is the assignment...
Write a program that will input four students’ names and average five test grades for each student. The program should have an array for the students name and then a two-dimensional array for all their grades.
Your program should ask for the students name and then five test scores for that student.
Create a method that does the averaging and pass the arrays to that method. That method can also output the student name and average in a list box.
Call a method to figure up the average once you get all the grades. Do not figure it up as you get the information!! You’ll get a big ole zero if you do! Then have that same method output the results into the list box:
After 4 days of struggling with this, here is what I have come up with so far. Any guidance is greatly appreciated. Thank you in advance.
Public Class Form1
Private Sub btnNames_Click(sender As System.Object, e As System.EventArgs) Handles btnNames.Click
Dim NamesList(3) As String
Dim GradeArray(4) As Integer
Dim x As Integer
Dim y As Integer
Dim Sum As Integer
Dim Avg As Integer
For y = 0 To NamesList(3)
NamesList(x) = InputBox("Enter student number " & y + 1 & "'s name:", "Enter a name")
Next
For y = 0 To GradeArray.Length - 1
GradeArray(y) = InputBox("Enter grade number " & y + 1 & " for " & NamesList(0) & " in the box:", "Enter the grades")
Next
For Each item In GradeArray
Sum = Sum + item
Next
Avg = Sum / 5
lstAverages.Text = Avg.ToString
End Sub
Private Sub btnExit_Click(sender As System.Object, e As System.EventArgs) Handles btnExit.Click
Me.Close()
End Sub
End Class
I had nothing else better to do, so I took up giving it a try... Also this includes per as you stated: 4 students - 5 grades each, array for students names and a 2D array to hold all their grades. There's a method that passes these to it and performs the averaging of the students grades and then spits them to a listbox as requested ... Happy Coding!
P.S. I didn't do any error handling either, you may want to add that or at least implement something to handle such cases ...
Public Class Form1
Private arrStudents(3) As String 'Student's name array (4)
Private arrScores(3, 4) As Integer 'Students scores (5 each)
'Start getting the data we need
Private Sub btnGetStudents_Click(sender As Object, e As EventArgs) Handles btnGetStudents.Click
Dim strStudent As String = String.Empty
Dim intScore As Integer = 0
Dim intPlace As Integer = 0
'Get the students name...
For i As Integer = 0 To arrStudents.Length - 1
Do Until strStudent <> String.Empty
strStudent = InputBox("Please enter student's name: ", "Gather Student Grades")
Loop
arrStudents(i) = strStudent
'Reset our variable...
strStudent = String.Empty
'Get the students grades...
For s As Integer = 0 To arrScores.Length - 1
Do Until intScore > 0
intScore = CInt(InputBox("Please enter student's scores: ", "Gather Student Scores"))
Loop
If (intPlace = 4 AndAlso i = arrStudents.Length) Then
intPlace = 0
arrScores(i, s) = intScore
intScore = 0
ElseIf intPlace = 4 Then
intPlace = 0
arrScores(i, s) = intScore
intScore = 0
Exit For
Else
arrScores(i, intPlace) = intScore
intPlace += 1
End If
'Reset our variables...
intScore = 0
Next
Next
'Calculate and output the data to the listbox...
GetStudentAverages(arrStudents, arrScores)
End Sub
'Function to average per student grades and then display them all in the listbox...
Private Sub GetStudentAverages(ByVal arStudent As Array, ByVal arScore As Array)
Dim strStudentData As String = String.Empty
Dim intAverage As Integer = 0
Dim intPlace As Integer = 0
'Start averaging the students scores and then add them to the listbox...
For i As Integer = 0 To arStudent.Length - 1
For g As Integer = 0 To arScore.Length - 1
If intPlace = arStudent.Length Then
intAverage += arScore(i, intPlace)
Exit For
Else
intAverage += arScore(i, intPlace)
intPlace += 1
End If
Next
intAverage = CInt(intAverage / 5)
intPlace = 0
'Output the student information...
ListBox1.Items.Add("Student: " & arStudent(i).ToString & " Average: " & intAverage.ToString)
intAverage = 0
Next
End Sub
End Class

Resources