Arithmetic Quiz On VB - vb.net

I'm a beginner and need help with a school project. I'm trying to get the scores to show from highest to lowest and the average score. How can I do this? My current code is:
Dim filename As String
Dim numberofrecords As Short
Dim countofloop As Short
Dim one, two, three As Short
filename = "N:\Class1.dat"
FileOpen(1, filename, OpenMode.Random, , , Len(OneStudentScore))
numberofrecords = LOF(1) / Len(OneStudentScore)
countofloop = 0
Dim scores(numberofrecords) As Integer
Dim names(numberofrecords) As String
Do While (Not EOF(1))
FileGet(1, OneStudentScore)
one = OneStudentScore.score1
two = OneStudentScore.score2
three = OneStudentScore.score3
names(countofloop) = OneStudentScore.Name
If one > two Then
If one > three Then
'1st score is the biggest
scores(countofloop) = one
Else
scores(countofloop) = three
End If
Else
If two > three Then
scores(countofloop) = two
Else
scores(countofloop) = three
End If
End If
countofloop = countofloop + 1
Loop
'sort array into score order
Array.Sort(scores, names)
'this allows the arrays to be in descending order - highest first
Array.Reverse(scores)
Array.Reverse(names)
Dim displayeditem As String
lstClass1.Items.Clear()
'display the arrays in a list box
For i = 0 To countofloop
displayeditem = names(i) & " " & scores(i)
lstClass1.Items.Add(displayeditem)
FileClose()
Next
End Sub
End Class

I didn't run the code but it would appear that you are properly sorting the array to go from highest to lowest. If you just need the average then it should just be a matter of adding up the elements in the scores array and dividing by the number of elements. Something like:
Dim total As Integer = 0
Dim numScores As Integer = 0
For i As Integer = 0 To scores.Length - 1
total += scores(i)
numScores += 1
Next
Dim average As Integer
average = total / numScores

Related

How can put split integers in a two-dimensional array?

I making matrix calculator. so, Textbox_A contains vbCrLf and tries to put it in Array_A.
and I would like to put Array_A in Result Matrix.
It's like
Textbox_a:
(1 2 3)
(4 5 6)
[Matrix to Array]
Array_a(0)(0) = 1
Array_a(0)(1) = 2
Array_a(0)(2) = 3
Array_a(1)(0) = 4
...
I have done string splits through several articles, but changing them to integers causes many problems.
This picture is Matrix_A and result Matrix
I don't know if the size of your initial matrix, formatted as text, is fixed, but here is some code to help you get started. The code tries to calculate the number of columns and rows.
The actual code is in the TextToArray function, that takes as input as string formatted as you described:
(1 2 3) (cr/lf)
(4 5 6)
and outputs a two dimensional array. The Main sub is just used to call TextToArray and display results.
So, in your example, you should pass TextBox_A.Text to TextToArray
There is minimal error checking here - you should add more to validate that data entered are numbers (check the Integer.TryParse function) and that the number of columns is the same across lines.
Sub Main(args As String())
Dim myInput As String = "(1 2 3)" & vbCrLf & "(4 5 6)"
Dim ret As Integer(,) = TextToArray(myInput)
If ret IsNot Nothing Then
For i As Integer = 0 To ret.GetUpperBound(0) - 1
For n As Integer = 0 To ret.GetUpperBound(1) - 1
Console.WriteLine(i & "," & n & "=" & ret(i, n))
Next
Next
Else
Console.WriteLine("No results - wrong input format")
End If
Console.ReadLine()
End Sub
Private Function TextToArray(matrix As String) As Integer(,)
Dim noOfRows As Integer = matrix.Split(vbCrLf).Count
Dim noOfColumns As Integer = 0
If noOfRows > 0 Then
noOfColumns = matrix.Split(vbCrLf)(0).Split(" ").Count
End If
If noOfColumns > 0 And noOfRows > 0 Then
Dim ret(noOfRows, noOfColumns) As Integer
Dim lines As String() = matrix.Split(vbCrLf)
Dim row As Integer = 0
For Each line As String In lines
Dim col As Integer = 0
line = line.Replace("(", "")
line = line.Replace(")", "")
For Each s As String In line.Split(" ")
ret(row, col) = Integer.Parse(s)
col += 1
Next
row += 1
Next
Return ret
Else
Return Nothing
End If
End Function
This outputs:
0,0=1
0,1=2
0,2=3
1,0=4
1,1=5
1,2=6

How to remove the two lowest grades from the listbox before the total grades are calculated?

I am trying to remove the two lowest grades from the listbox before the average and total of the grades is calculated using Visual Basic form application
I know I need to sort the array but I need to sort it after the listbox has been filled and before the average grade and total grade is calculated.
Please ignore the intMaxNumberOfEntries as 3. I will change it to 13 once I get the code working right.
' The btnEnterGrades_Click event accepts and displays up to 13 grades
' and then calculates and displays the average grade for the student
' Declare and initialize variables
Dim strGrade As String
Dim intSizeOfArray As Integer = 3
Dim decGrade(intSizeOfArray) As Decimal
Dim decAverageGrade As Decimal
Dim decTotalGrades As Integer = 0D
Dim strInputMessage As String = "Enter the grade to be averaged #"
Dim strInputHeading As String = "Enter Grades"
Dim strNormalMessage As String = "Enter the grade to be averaged #"
Dim strNonNumericError As String = "Error - Enter a number for the grade to be averaged"
Dim strNegativeError As String = "Error - Enter a positive number for the grade to be averaged"
Dim objWriter As New IO.StreamWriter("grades.txt")
'Declare and initialize loop variables
Dim strCancelClicked As String = ""
Dim intMaxNumberOfEntries As Integer = 3
Dim intNumberOfEntries As Integer = 1
' This loop allows the user to enter up to 13 grades for the student.
' The loop terminates when the user has entered 13 grades or the user
' taps or clicks the Cancel button or the Close button in the InputBox
'"Primimg the Loop" Accept some value and place it into the strGrade
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
strGrade = InputBox(strInputMessage & intNumberOfEntries, strInputHeading, " ")
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Determining if Grade entered is numeric. If so, add the item to the listbox
Do Until intNumberOfEntries > intMaxNumberOfEntries Or strGrade = strCancelClicked
If IsNumeric(strGrade) Then
decGrade(intSizeOfArray) = Convert.ToDecimal(strGrade)
If decGrade(intSizeOfArray) > 0 Then
'''''''''''''''''''''''''''''''''''''''''''
lstGrades.Items.Add(decGrade(intSizeOfArray))
'''''''''''''''''''''''''''''''''''''''''''
End If
'Accumulator and Counter??
decTotalGrades += decGrade(intSizeOfArray)
intNumberOfEntries += 1 'or IntNumberOfEntries = intNumberOfEntries + 1
strInputMessage = strNormalMessage
Else
strInputMessage = strNegativeError
End If
Else
strInputMessage = strNonNumericError
End If
If intNumberOfEntries <= intMaxNumberOfEntries Then
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
strGrade = InputBox(strInputMessage & intNumberOfEntries, strInputHeading, " ")
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
End If
Loop
'Sort the Array
Array.Sort(decGrade)
'Put in descending order
Array.Reverse(decGrade)
'Drop 2 lowest scores of array
ReDim decGrade(1)
'Calculates and displays average student grade
If intNumberOfEntries > 1 Then
lblFinalAverageText.Visible = True
decAverageGrade = decTotalGrades / (intNumberOfEntries - 1)
lblFinalAverageText.Text = "The Final Average is: " &
decAverageGrade.ToString("F1")
Else
MsgBox("No grade entered")
End If
I want the program to remove the two lowest grades and I wrote code to sort the array and then sort by descending order and then redim to remove the two lowest grades but I realized the program is adding grades to the decTotalGrades before I start the sorting and redim process. I do not know how to rearrange this code for it to work.
You could refresh the list after collecting all grades and sorting/removing items.
'Collect grades.
Dim grades As New List(Of Decimal)
While grades.Count < 13
Dim strGrade As String = InputBox("Enter the grade to be averaged #" &
grades.Count, "Enter Grades")
If String.IsNullOrEmpty(strGrade) Then
Exit While
Else
Dim grade As Decimal
If Decimal.TryParse(strGrade, grade) Then
grades.Add(grade)
lstGrades.Items.Add(grade)
End If
End If
End While
'Perform logic on the complete list of grades; Sort and remove.
'...
'Show the final list of grades.
lstGrades.Items.Clear()
For Each grade In grades
lstGrades.Items.Add(grade)
Next

Does this code not work because it will take a long time or is it broken?

I am currently trying to generate random numbers until a user defined amount of identical numbers in a row appears. The numbers range from 1 to 10.
When I want 8 identical numbers in a row it takes between 3 and 5 seconds. It goes through about 5 million random numbers. When I want 9 in a row I have left it for over 45 minutes without any luck.
I thought it would only take about 10 times the amount of time as it did for 8 since 1/10 to the power of 9 is only ten times bigger than to the power of 8.
Is it a problem with my code or have I messed up the maths?
MY CODE:
Sub Main()
Console.WriteLine("how many identical numbers in a row do you want")
Dim many As Integer = Console.ReadLine
Dim storage(many - 1) As Integer
Dim complete As Boolean = False
Dim part As Integer = 0
Dim count As Integer = 0
Randomize()
While complete = False
count += 1
storage(part) = Int(Rnd() * 10) + 1
' Console.WriteLine(storage(part))
part += 1
If part = many Then
part = 0
End If
If storage.Min = storage.Max Then
complete = True
End If
End While
Console.WriteLine("===========")
Console.WriteLine(count.ToString("N"))
Console.WriteLine("===========")
For i = 0 To many - 1
Console.WriteLine(storage(i))
Next
Console.ReadLine()
End Sub
There is more than one possibility: it could be that the VB Rnd function is written so that it can never work, or it could be that it really does simply take a long time sometimes. You would have to do many trials and average them out to find out if your expected ratio of 1:10 works as expected.
Incidentally, you don't need to keep the last ten numbers. You can just keep a count of how many times the next random number equals the previous number. Also I suggest trying a different RNG (random number generator), for example the .NET one:
Module Module1
Dim rand As New Random()
Sub Main()
Console.Write("How many identical numbers in a row do you want: ")
Dim howMany As Integer = CInt(Console.ReadLine)
Dim count As Long = 0
Dim previous = -1
Dim soFar = 0
Dim n = 0
While soFar < howMany
count += 1
n = rand.Next(1, 11)
'Console.Write(n.ToString() & " ")
If n = previous Then
soFar += 1
Else
'If previous >= 0 Then
' Console.WriteLine(" X")
' Console.Write(n.ToString() & " ")
'End If
previous = n
soFar = 1
End If
End While
Console.WriteLine()
Console.WriteLine("Tries taken: " & count.ToString())
Console.ReadLine()
End Sub
End Module

How to remove the two lowest numbers from a listbox in Visual Basic 2015?

Ok so I'm supposed to have the user input up to 13 grades, then have them averaged after removing the two lowest grades. I can't figure out what to use to remove the two lowest grades, whether it be from the listbox or during the calculation. Here's my code so far:
Dim strGrades As String
Dim decGrades As Decimal = 0
Dim decAverage As Decimal = 0
Dim decTotal As Decimal = 0
Dim strInputMessage As String = "Enter grade #"
Dim strInputHeading As String = "Grade"
Dim strNormalMessage As String = "Enter grade #"
Dim strNonNumericError As String = "Error - Please enter a grade"
Dim strNegativeError As String = "Error - Please enter a positive number"
Dim strCancelClicked As String = ""
Dim intMaxNumberOfEntries As Decimal = 13
Dim intNumberOfEntries As Decimal = 1
strGrades = InputBox(strInputMessage & intNumberOfEntries, strInputHeading, " ")
Do Until intNumberOfEntries > intMaxNumberOfEntries Or strGrades = strCancelClicked
If IsNumeric(strGrades) Then
decGrades = Convert.ToDecimal(strGrades)
If decGrades >= 0 Then
lstGrades.Items.Add(decGrades)
decTotal += decGrades
intNumberOfEntries += 1
strInputMessage = strNormalMessage
Else
strInputMessage = strNegativeError
End If
Else
strInputMessage = strNonNumericError
End If
If intNumberOfEntries <= intMaxNumberOfEntries Then
strGrades = InputBox(strInputMessage & intNumberOfEntries, strInputHeading, " ")
End If
Loop
lstGrades.Sorted = True
Assuming that you have an enumerable list of numeric values, e.g. an array of Decimal, then the most succinct way to get the average of all but the two lowest values would be:
Dim average = myList.OrderBy(Function(n) n).Skip(2).Avg()
I'm not sure how much of that would be acceptable for an assignment - if that's what this is - but the part that you're asking about specifically can still be done by calling Skip(2) if you start with a list that is sorted in ascending order.
You can count the entries in the list box and remove the bottom 2 entries.
You can add them to a list and sort it.

VB 2008 (Console) "For Each Loop" Lottery Results Comparison

I am facing an issue to perform numbers comparison between the integers inputted by user and random numbers generated by the codes.
Each of the integers input by the user should then be compared with the LOTTO numbers to check for a match. A For each… loop needs to be used to achieve this.
After checking all the 7 user input integers against the LOTTO numbers, the total number of matches should be output to the user. If there are no matches the output should read “LOOSER!”.
Here are my codes, I'm currently only stuck at the comparison portion, and we need to use for each loop to achieve this.
Imports System
Module Lotto
Sub Main()
'Declaration
Dim numbers(6) As Integer
Dim IsStarted As Boolean = True
'Prompt user to enter
Console.WriteLine("Please enter your 7 lucky numbers from 0 - 9 ONLY")
'Use Do While Loop to re-iterate the prompts
Do While IsStarted
For pos As Integer = 0 To 6
Console.Write("Enter number {0}: ", pos + 1)
'How it stores into an array
numbers(pos) = Console.ReadLine()
'Check if it is a number: use IsNumberic()
If IsNumeric(numbers(pos)) Then 'proceed
'Check if it is NOT 0 < x > 9
If numbers(pos) < 0 Or numbers(pos) > 9 Then
'Don't proceed
Console.WriteLine("Invalid Input")
IsStarted = True
'When any number is invalid, exit the loop
Exit For
End If
End If
IsStarted = False
Next
Loop
'Printing out the array. It can also be written as
'For pos = LBound(numbers) To UBound(numbers)
For pos = 0 To 6
Console.Write(numbers(pos) & " ")
Next
Console.WriteLine()
'Random number generator
Randomize()
Dim random_numbers(6) As Integer
Dim upperbound As Integer = 7
Dim lowerbound As Integer = 0
Dim rnd_number As Double = 0
For pos = 0 To 6
rnd_number = CInt((upperbound - lowerbound) * Rnd() + lowerbound)
random_numbers(pos) = rnd_number
Console.Write(random_numbers(pos) & " ")
Next
'Iterate and compare
Dim isSame As Boolean = False
Dim pos2 As Integer = 0
Dim Counter As Integer = 0
'For check = 0 To 6
'If numbers(pos2).Equals(random_numbers(pos2)) Then
For Each number As Integer In numbers
'Console.WriteLine(pos2 + 1 & ":" & number & ":")
If number.Equals(random_numbers(pos2)) Then
'Console.WriteLine("here is the number that matched:" & number & ":")
isSame = True
pos2 = pos2 + 1
End If
For Each num As Integer In random_numbers
If random_numbers Is numbers Then
Counter = Counter + 1
End If
Next
Next
Console.WriteLine()
'Display result
If isSame = True Then
Console.WriteLine("The total numbers of matches are: " & Counter)
Else
Console.WriteLine("LOOSER!")
End If
Console.ReadLine()
End Sub
End Module
Dim intCursor As Integer = 0
For Each intNumber As Integer In numbers
'Assumes first user chosen number must equal
'the first random number to be considered a match,
'the second user number must equal the second random,
'etc (Ordering is a factor).
If random_numbers(intCursor) = intNumber Then
Counter += 1
End If
intCursor += 1
Next
If (Counter > 0) Then
Console.WriteLine("The total numbers of matches are: " & Counter)
Else
Console.WriteLine("LOOSER!")
End If