Will not display in list box VB - arrays

So, I'm trying to display the statistics for a soccer teams points scored.
At the time this is being executed, the arrays have been already filled and what not.
When this form opens, I'd like it to display the maximum, minimum, and average scores....
I want it to get the players name and score for max and min. For example:
Maximum: John scored 9
Minimum: Joe scored 2
Like, i'd be getting the value at strPlayers(i) for the name and intScores(i) for score.
I'm pretty sure I had the functions correct, but, for whatever reason, I can not get it to display anything in the list box upon loading the form!
Public Class frmDisplayStatistics
Function FindMaximum() As String
Dim max As Integer
Dim i As Integer = 0
ReDim intScores(intNumberOfPlayers)
max = CInt(intScores(0))
For i = 0 To intNumberOfPlayers
If max < intScores(i) Then
max = CInt(intScores(i))
End If
Next
max = strPlayers(i) & " scored maximum points of " & intScores(i)
Return max
End Function
Function FindMinimum() As Integer
Dim min As Integer
Dim i As Integer = 0
ReDim intScores(intNumberOfPlayers)
min = CInt(intScores(0))
For i = 0 To intNumberOfPlayers
If min > intScores(i) Then
min = CInt(intScores(i))
End If
Next
Return min
End Function
Function FindAverage() As Double
Dim average As Double
Dim i As Integer = 0
average = total / intNumberOfPlayers
Return average
End Function
Private Sub frmDisplayStatistics_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim max As String
max = FindMaximum()
lstStatistics.Items.Add(max)
lstStatistics.Items.Add("Minimum: " & FindMinimum())
lstStatistics.Items.Add("Average: " & FindAverage())
End Sub
Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
Me.Close()
End Sub
End Class
The reason maximum returns a string and minimum and average return a number is because I was trying a different approach, that also did not work. :/

Assuming you are getting array in the variable max in the form load event. Then you should loop the array. Like below
for i = 0 to max.count -1
listbox.item.add(i)
next
Also you need to declare variable max as array. Hope you got my point

Related

Why is it not comparing my array to my input properly and adding up how many in the array are greater or = to the input

The program is supposed to search through the array and add up how many in the array are = to or greater than the users input, but no matter what I put in it says all 5 arrays are. On the other hand, I input 0 it gives me 0 even though all five are greater than 0.
Here is my code please explain what's wrong and how to fix it.
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles Me.Load
'fills the array
intSales(0) = 5000
intSales(1) = 4500
intSales(2) = 2000
intSales(3) = 6000
intSales(4) = 3000
End Sub
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
' searches the intSales array, looking for values that are
' greater than or equal to the value entered by the user
'names the veriables
Dim intSales_amount As Integer
Dim intEmployee As Integer
'stores the variables
Integer.TryParse(txtSales.Text, intSales_amount)
Integer.TryParse(lblCount.Text, intEmployee)
'sets counter to 0
intEmployee = 0
'searches the array and counts how many of the values are
' greater than or equal to the value entered by the user
' and stores it in the counter
For intsub As Integer = 0 To intSales.Length - 1
If intSales_amount >= intSales.Length Then
intEmployee += 1
End If
Next intsub
'displays amount stored in the counter
lblCount.Text = intEmployee
End Sub
here is where I think the problem is
For intsub As Integer = 0 To intSales.Length - 1
If intSales_amount >= intSales.Length Then
intEmployee += 1
End If
Next intsub
Your loop that is supposed do do the checking ..
For intsub As Integer = 0 To intSales.Length - 1
If intSales_amount >= intSales.Length Then
intEmployee += 1
End If
Next intsub
is only checking if intSales_amount is greater than or equal to the number of elements in the array, not the amount that is in each element. To check it against the contents of each element in the array change it to this :-
If intSales_amount >= intSales(intsub) Then
I'm assuming that the values in the intSales array are a number relating the each salesperson's sales. If you're trying to find out how many salespersons have sales above the intSales amount, then your test is the wring way round. It should be :-
If intSales(intsub) >= intSales_amount Then
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
' searches the intSales array, looking for values that are
' greater than or equal to the value entered by the user
Dim intSales_amount As Integer
If Integer.TryParse(txtSales.Text, intSales_amount) Then
lblCount.Text = intSales.Count(Function(s) s >= intSales_amount)
Else
'If you're not gonna do something different if TryParse() fails,
' you may just as well use plain Parse()
End If
End Sub

How to monitor array's and reset when limit is reached. VB.net

I have a VB.Net program that loops through array's to try to figure out where bottles are on a "conveyor". The point of this program is to visually show staff, how the conveyor works using VB.net and Labels. It's extremely difficult to explain, so I’ll do my best.
Bottle_Number(10) Bottle_Position(128)
There are 10 bottles that I want to track at all 128 stops on the conveyor.
We have a conveyor that can only fit 10 bottles. I need to track the position of each of the 10 bottles. Once bottle 11 comes on - That means bottle 1 is completed and off the conveyor. So, bottle 11 becomes bottle 1, so I need to reset the position of bottle1 to 0, and continue tracking bottles 2-9 while also tracking bottle 11(Not bottle 1). Once bottle 12 comes on it becomes bottle 2, and I need to reset the position of bottle 2 to '0' and continue tracking all bottles.
Any help would be appreciated.
Here is my code:
Public Class frmMain
Dim Product_Position(10) As Integer
Dim Inches_Per_Pulse As Integer
Dim PulseNumber As Integer
Dim Product_Counter As Integer
Dim Product_Location(10) As Integer
Dim Function1 As Integer
Dim Function2 As Integer
Dim Function3 As Integer
Dim Function4 As Integer
Dim Function5 As Integer
Dim Function6 As Integer
Dim Function7 As Integer
Dim Function8 As Integer
Dim Function9 As Integer
Dim Function10 As Integer
Dim Product_in_Tunel As Integer
Dim test As Integer
Dim Roll_OVer As Boolean
Dim Product_Counter_Test As Integer
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
lblStatus.BackColor = Color.Green
lblStatus.Text = "Conveyor Status: Running"
End Sub
Private Sub btnStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStop.Click
lblStatus.BackColor = Color.Red
lblStatus.Text = "Conveyor Status: Off"
End Sub
Private replace_next As Integer
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
If Product_Counter = 10 Then
replace_next += 1
If replace_next > 10 Then
replace_next = 1 ' replace them in turn 1..10, then loop back to 1
Product_Position(replace_next) = 0 ' put initial position here
End If
End If
Product_Counter = Product_Counter + 1
If Product_Counter > 10 Then
Product_Counter = 1
Roll_over = True
End If
'MsgBox(Product_Counter)
'MsgBox(replace_next)
End Sub
Private Sub btnPulse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPulse.Click
Get_Location()
End Sub
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
PulseNumber = "0"
Inches_Per_Pulse = "1"
Roll_OVer = False
'MsgBox("Test")
End Sub
Public Sub Get_Location()
'MsgBox(Product_Counter)
If Roll_OVer = True Then
Product_Counter_Test = 10
'MsgBox("i'm stuck here")
End If
If Roll_OVer = False Then
Product_Counter_Test = Product_Counter
End If
'MsgBox(Product_Counter_Test)
'MsgBox("am I here - Yes")
For test = 1 To Product_Counter_Test
'MsgBox("This works")
Product_Position(test) = Product_Position(test) + Inches_Per_Pulse
Next
PulseNumber = PulseNumber + 1
ClearLabels()
lblProduct1Position.Text = Product_Position(1)
lblProduct2Position.Text = Product_Position(2)
lblProduct3Position.Text = Product_Position(3)
lblProduct4Position.Text = Product_Position(4)
lblProduct5Position.Text = Product_Position(5)
lblProduct6Position.Text = Product_Position(6)
lblProduct7Position.Text = Product_Position(7)
lblProduct8Position.Text = Product_Position(8)
lblProduct9Position.Text = Product_Position(9)
lblProduct10Position.Text = Product_Position(10)
End Sub
Public Sub ClearLabels()
lblProduct1Position.Text = ""
lblProduct2Position.Text = ""
lblProduct3Position.Text = ""
lblProduct4Position.Text = ""
lblProduct5Position.Text = ""
lblProduct6Position.Text = ""
lblProduct7Position.Text = ""
lblProduct8Position.Text = ""
lblProduct9Position.Text = ""
lblProduct10Position.Text = ""
End Sub
The Pulse button is what is actually driving the conveyor, each pulse (click of the button) means the conveyor is moving forward.
Right now once the program gets to bottle 11, it resets and only moves forward the "new" bottle (bottle1). It should continue incrementing the remaining bottles until they reach the end and do the same for them - Reset the position to 0 and begin counting again.
As far as I understand it, once you have 11 bottles, you don't want to reset to only one bottle, but instead still have 10 bottles, and replace one of them. You'll need a second variable to keep track of which is to be replaced.
So instead of :
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
Product_Counter = Product_Counter + 1
If Product_Counter > 10 Then Product_Counter = 1
End Sub
It would be something like:
Private Replace_Next as Integer = 0
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
If Product_Counter = 10 Then
Replace_Next += 1
If Replace_Next > 10 Then Replace_Next = 1 ' replace them in turn 1..10, then loop back to 1
Product_Position(Replace_Next) = .... ' put initial position here
Else
Product_Counter = Product_Counter + 1
End If
End Sub
Your conveyor is FIFO (first-in, first-out), so rather than constantly shifting, reindexing and/or rebuilding (=reset?) an array to make it seem like it is FIFO, Net includes the Queue(Of T) collection which is FIFO.
A LinkedList(Of T) could also be used. A plain List(Of T) would also work, but if the add/remove frequency is high, that will result in the same inefficient shifting taking place under the hood that you have with an array.
The only issue is enforcement of the size limit, which is easily handled with a small class wrapper. I assume there is something interesting or identifiable about the bottles other than their position. The test code uses a sequence ID and the contents.
Friend Class Bottle
Public Property Contents As String
Public Property SequenceID As Int32
' etc
Public Overrides Function ToString() As String
Return String.Format("{0}: ({1})", SequenceID.ToString("00"), Contents)
End Function
End Class
You likely have more relevant information to show. The, the collection class:
Friend Class BottleQueue
Private mcol As Queue(Of Bottle)
Private lbls As Label()
Private MaxSize As Int32 = 10 ' default
Public Sub New(size As Int32)
MaxSize = size
mcol = New Queue(Of Bottle)
End Sub
Public Sub New(size As Int32, l As Label())
Me.New(size)
lbls = l
End Sub
Public Sub Add(b As Bottle)
mcol.Enqueue(b)
Do Until mcol.Count <= MaxSize
mcol.Dequeue()
Loop
UpdateDisplay()
End Sub
Public Function Peek() As Bottle
Return mcol.ElementAtOrDefault(0)
End Function
Public ReadOnly Property Count() As Int32
Get
Return mcol.Count
End Get
End Property
Public Function Remove() As Bottle
Dim b As Bottle = Nothing
If mcol.Count > 0 Then
b = mcol.Dequeue
UpdateDisplay()
End If
Return b
End Function
Private Sub UpdateDisplay()
Dim n As Int32
If lbls Is Nothing OrElse lbls.Count = 0 Then
Return
End If
For n = 0 To mcol.Count - 1
lbls(n).Text = mcol.ElementAtOrDefault(n).ToString
Next
For n = n To lbls.Count - 1
lbls(n).Text = "(empty)"
Next
End Sub
Public ReadOnly Property GetQueue As Bottle()
Get
Return mcol.ToArray()
End Get
End Property
End Class
The class has 2 display means built in. One updates a set of labels. Since it is a collection, it also provides a way to get the current collection in order for a collection type control such as a Listbox. An even better way would be if the collection itself was "observable", so it could be used as a datasource.
It also provides a way to Removethe next bottle manually. Removing from a specific index (e.g. Remove(3)) is antithetical to a Queue, so it isnt implemented.
test code:
' form level vars:
Private BottleQ As BottleQueue
Private BottleID As Int32 = 7
' form load, passing the labels to use
' using a queue size of FIVE for test
BottleQ = New BottleQueue(5, New Label() {Label1, Label2, Label3, Label4, Label5})
Adding an item:
Dim material = {"Napalm", "Beer", "Perfume", "Pepsi", "Cyanide", "Wine"}
' add new bottle with something in it
BottleQ.Add(New Bottle With {.Contents = material(RNG.Next(0, material.Count)),
.SequenceID = BottleID})
BottleID += 1
' clear and show the contents in a listbox:
lbQueView.Items.Clear()
lbQueView.Items.AddRange(BottleQ.GetQueue)
The BottleId arbitrarily starts at 7, the contents are random. BTW, material shows just about the only way I ever use an array: when the contents are fixed and known ahead of time. In almost all other cases, a NET collection of one sort or another, is probably a better choice.
Because it is not an observable collection (and that is a little at odds with the FIFO nature), the listbox needs to be cleared each time. That could be internal to the class like the label display is. Results:
On the right, the first 5 are shown in order; 3 clicks later, the result is on the left: everything moved up 3 and 3 new items have been added.
Note: If the code using this needs to know when/which Bottle is removed from the conveyor, the class could include a ItemRemoved event which provides the item/Bottle just removed when adding forces one out. That is probably the case, but the question doesnt mention it.

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

There is an error in my code, '1- dimensional array of double cannot be converted too boolean'

Sorry i'm new to all this, i don't know how to fix my bubble sort , i have an array but i have 2 errors in my code, so i don't even know if it works or how to fix it help would be very much appreciated.
My first error said '1- dimensional array of double cannot be converted too boolean' and second error said 'identifier expected' Both errors occur on line 23
'Declares the name of the sorted Array
Dim SortedArray(49) As Integer
'Declares the name for the Unsorted Array
Dim UnSortedArray(49) As Double
Private Sub BtnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStart.Click
'Declare Random Numbers, NumberRange and the Name of the array
Dim RandomNumber As New Random
Dim NumberRange As Integer
Dim swap As Boolean
'Declares the Values of the numbers only be between 0 and 100
Randomize(NumberRange)
For NumberRange = 0 To 49
Next
'Creates and Array with 100 RandomNumbers with values inbetween 0 and 100
SortedArray(NumberRange) = RandomNumber.Next(0, 100)
UnSortedArray(NumberRange) = UnSortedArray(NumberRange)
'Adds the items onto the ListBox
LstUnSorted.Items.Add(UnSortedArray(NumberRange).ToString)
swap = False
For i = 1 To UnSortedArray(49) - 1
If UnSortedArray ([i]-1) > UnSortedArray[i] Then
UnSortedArray(i - 1) = UnSortedArray([i])
swap = True
End If
Next
End Sub
End Class

How can I Calculate the Average of the Array List

Ok I need to get size of the array and the array inputs through a msgbox and display the array list in a list box and then get the average of the array list. here is the code I have so far:
Private Sub btnCalculate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
Dim i, size As Integer
size = Val(InputBox("Please enter array size"))
Dim sequence(size) As Integer
'get array values
i = 0
Do While i < size
sequence(i) = Val(InputBox("Please enter element of array"))
i = i + 1
Loop
i = 0
Do While i < size
lstoutArray.Items.Add(sequence(i))
i = i + 1
Loop
End Sub
While something like this will work:
Dim lstoutArray As New ArrayList
Dim lstoutCount As Double = 0
Dim size As Double
size = Val(InputBox("Please enter array size"))
For i = 1 To size
lstoutArray.Add(Val(InputBox("Please enter element of array")))
lstoutCount += DirectCast(lstoutArray(lstoutArray.Count - 1), Double)
Next
Dim lstoutAverage As Double = lstoutCount / lstoutArray.Count
You can see from this example that one of the main drawbacks to using an arraylist, is that it isn't strongly typed. Therefore to use the values in the arraylist you have to cast them as the type you need.
A List(Of) is much easier to use as it's strongly typed already and has the Average extension:
Dim lstoutArray As New List(Of Double)
Dim size As Double
size = Val(InputBox("Please enter array size"))
For i = 1 To size
lstoutArray.Add(Val(InputBox("Please enter element of array")))
Next
Dim lstoutAverage = lstoutArray.Average

Resources