I am very new to coding so please forgive me.
I have saved some example strings in an array:
Dim intArray(0 To 2) As String
intArray(0) = "I will be on time for class"
intArray(1) = "I will be prepared for class"
intArray(2) = "I will listen to the teacher and follow instructions"
lblTestSWPB.Text = intArray(0)
I know that it works when I click the button to generate for (0) - obviously.Is there a way to add something to make the label display a string at random from the array?
You may use something like: Random class
Dim rnd As New Random 'Make sure that you declare it as New,
'otherwise, it thorws an Exception(NullReferenceException)
Dim intArray(0 To 2) As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
intArray(0) = "I will be on time for class"
intArray(1) = "I will be prepared for class"
intArray(2) = "I will listen to the teacher and follow instructions"
End Sub
Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
lblTestSWPB.Text = intArray(rnd.Next(0, 3))
End Sub
Note that rnd.Next is a Function that returns a random Integer from the minimum is the inclusive lower bound and the maximum is the exclusive upper bound.(Thanks to #Enigmativity for the correction.) Click this link if this answer is still unclear for you
Related
I am trying to stay ahead of my Year 12 Software class. Starting to work with records and arrays. I have answered the question, but the solution feels very clunky. I am hoping someone has suggestions/links for completing this task in a more efficient way.
The task: read in lines from a text file and into a structure, and then loop through that, populating four list boxes if an animal hasn't been vaccinated.
Here's the code:
Imports System.IO
Public Class Form1
'Set up the variables - customer record, total pets not vaccinated, total records in the file, and a streamreader for the file.
Structure PetsRecord
Dim custName As String
Dim address As String
Dim petType As String
Dim vacced As String
End Structure
Dim totNotVac As Integer
Dim totalRecCount As Integer
Dim PetFile As IO.StreamReader
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub btnLoad_Click(sender As Object, e As EventArgs) Handles btnLoad.Click
'set an array of records to store each record as it comes in. Limitation: you need to know how many records in the file. Set the array at 15 to allow for adding more in later.
Dim PetArray(15) As PetsRecord
'variables that let me read in a line and split it into sections.
Dim lineoftext As String
Dim i As Integer
Dim arytextfile() As String
'tell them what text file to read
PetFile = New IO.StreamReader("patients.txt")
totNotVac = 0
Try
totalRecCount = 0
' read each line in and split the lines into fields for the records. Then assign the fields from the array. Finally, reset the array and loop.
Do Until PetFile.Peek = -1
'read in a line of text
lineoftext = PetFile.ReadLine()
'split that line into bits separated by commas. these will go into the array.
arytextfile = lineoftext.Split(",")
'dunno whether this is the best way to do it, but stick the array bits into the record, and then clear the array to start again.
PetArray(totalRecCount).custName = arytextfile(0)
PetArray(totalRecCount).address = arytextfile(1)
PetArray(totalRecCount).petType = arytextfile(2)
PetArray(totalRecCount).vacced = arytextfile(3)
totalRecCount += 1
Array.Clear(arytextfile, 0, arytextfile.Length)
Loop
For i = 0 To PetArray.GetUpperBound(0)
If PetArray(i).vacced = "No" Then
lstVaccinated.Items.Add(PetArray(i).vacced)
lstCustomer.Items.Add(PetArray(i).custName)
lstAddress.Items.Add(PetArray(i).address)
lstPetType.Items.Add(PetArray(i).petType)
totNotVac += 1
lblVacTotal.Text = "The total number of unvaccinated animals is " & CStr(totNotVac)
End If
Next
Catch ex As Exception
MsgBox("Something went wrong with the file")
End Try
PetFile.Close()
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Close()
End Sub
End Class
And one line from the patient.txt file:
Richard Gere,16 Sunset Blvd,Gerbil,No
I hope this isn't out of place.
Regards,
Damian
If you want to use Streams be aware that they need to be disposed.
File.ReadAllLines returns an array of lines. Since the array is initialized where it is declared we don't need to specify a size.
If you use List(Of T) you do not have to know in advance the number of elements in the list. Avoids the limitation of array.
Using a For Each avoids having to use the size. The small c following "," tells the compiler that this is a Char which is what .Split is expecting. If you had Option Strict On, which you always should, you would have seen an error. You add items to the list by creating a New PetsRecord. The parametrized Sub New receives the values and sets the properties.
Don't change the display in the label on each iteration. Use an interpolated string (preceded by a $) which allows embedded variables surrounded by braces { }. It is not necessary to change the number to a string as it is implied by the interpolator. (Available in VS2015 and later)
Public Structure PetsRecord
Public Property custName As String
Public Property address As String
Public Property petType As String
Public Property vacced As String
Public Sub New(name As String, add As String, pType As String, vac As String)
custName = name
address = add
petType = pType
vacced = vac
End Sub
End Structure
Private Sub btnLoad_Click(sender As Object, e As EventArgs) Handles btnLoad.Click
Dim lines = File.ReadAllLines("patients.txt")
Dim lstPet As New List(Of PetsRecord)
For Each line In lines
Dim splits = line.Split(","c)
lstPet.Add(New PetsRecord(splits(0), splits(1), splits(2), splits(3)))
Next
Dim totNotVac As Integer
For Each pet In lstPet
If pet.vacced = "No" Then
lstVaccinated.Items.Add(pet.vacced)
lstCustomer.Items.Add(pet.custName)
lstAddress.Items.Add(pet.address)
lstPetType.Items.Add(pet.petType)
totNotVac += 1
End If
Next
lblVacTotal.Text = $"The total number of unvaccinated animals is {totNotVac}"
End Sub
If you don't need the 'PetsRecord' array to store data, take a look at the following code:
Dim totNotVac As Integer
Private Sub btnLoad_Click(sender As Object, e As EventArgs) Handles btnLoad.Click
File.ReadAllLines("your text file path").ToList().ForEach(Sub(x)
lstVaccinated.Items.Add(x.Split(","c)(0))
lstCustomer.Items.Add(x.Split(","c)(1))
lstAddress.Items.Add(x.Split(","c)(2))
lstPetType.Items.Add(x.Split(","c)(3))
totNotVac += 1
End Sub)
lblVacTotal.Text = "The total number of unvaccinated animals is " & CStr(totNotVac)
End Sub
I am new to coding with visual basic.
Recently, I was tasked by my professor to write a programme that allows the user to enter five words. The words then should be sorted and displayed in alphabetical order.
To do this I decided the best approach would be to use an array.
My thinking was that if I created a counter at the start, I can create a different value for each column of the array when a button is clicked.
If the array exceeds five I have a message box pop-up that resets the code (although I realise I will also have to clear the contents of the array).
My problem arises in displaying the array. I have looked for solutions online, and none have helped me as of yet.
I need to sort the array into alphabetical order and then display it in a label box (lbl_DisplayArray). As I do not know the values of the array, this has proved tricky.
My code is below:
Public Class Form1
Dim i As Integer = 0
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim Array(4) As String
Array(i) = txt_UserWords.Text
End Sub
Private Sub btn_Next_Click(sender As Object, e As EventArgs) Handles btn_Next.Click
i += 1
If i >= 5 Then
i = 0
MsgBox("Array Limit Exceeded. Code Reset")
txt_UserWords.Text = ""
End If
End Sub
Private Sub btn_Sort_Click(sender As Object, e As EventArgs) Handles btn_Sort.Click
lbl_DisplayArray.Text =
End Sub
End Class
You'd be better off using
private myList as new List(of String).
Then to sort them you just call the .Sort() method. Just call .Add(txt_userWords.Text) to add the new string and use .Count to see how many of them you have.
When you're adding them to the label you can use
lbl_DisplayArray.Text = String.Join(vbCrLf, myList)
You'll need the list of to be a member of the class instead of a local variable (as you have declared Array). This will keep it alive and allow you to access it in other methods.
---------- edit ----------
Public Class Form1
private myList as new List(of String)
Private Sub btn_Next_Click(sender As Object, e As EventArgs) Handles btn_Next.Click
If myList.Count >= 5 Then
myList.Clear
Else
myList.add(txt_UserWords.Text)
End If
txt_UserWords.Text = ""
End Sub
Private Sub btn_Sort_Click(sender As Object, e As EventArgs) Handles btn_Sort.Click
myList.Sort()
lbl_DisplayArray.Text = String.Join(vbcrlf, myList)
End Sub
End Class
Trying to knock out a project that's hanging my code without re-writing the entire thing. In it, I just need to populate an array with the information already in the Names combobox in order to proceed. As I'm not using .NET, my options are limited.
(The end result)*Add a button named “btnShowBalance” displaying the text “ShowBalance.” Write code in its event handler asking the user to enter a client’s name (InputBox). Search the names array for the name entered. If the name is found, use its location to retrieve the matching balance from the balances array. Display the client’s name and balance if the client exists; otherwise, display a not-found message. ****
Public Class Form1
Dim Balances(7) As Decimal
Dim Names(7) As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cboNames.Items.Add("John One")
cboNames.Items.Add("Jack Two")
cboNames.Items.Add("John Three")
cboNames.Items.Add("Jack Four")
cboNames.Items.Add("John Five")
cboNames.Items.Add("Jack Six")
cboNames.Items.Add("John Seven")
cboNames.Items.Add("Jack Eight")
cboBalances.Items.Add("235.50")
cboBalances.Items.Add("78943.98")
cboBalances.Items.Add("230781.10")
cboBalances.Items.Add("78362.00")
cboBalances.Items.Add("12097.20")
cboBalances.Items.Add("89267.34")
cboBalances.Items.Add("34959.06")
cboBalances.Items.Add("559284.50")
For i = 0 To cboNames.Items.Count - 1
Names(i) = cboNames.Text
Next
For i = 0 To cboBalances.Items.Count - 1
Names(i) = cboBalances.SelectedItem
Next
End Sub
Private Sub btnShowBalance_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShowBalance.Click
Dim strResult As String
strResult = InputBox("Enter the name of the customer", "Balance Finder")
For i = 0 To Names.Length - 1
If strResult = Names(i) Then
MessageBox.Show(Names(i).ToString & " " & Balances(i).ToString)
End If
Next
End Sub
End Class
Dim Cans(7) As String
Dim money As Decimal
Public Sub Main()
Cans(0) = "Pepsi"
Cans(1) = "Pepsi MAX"
Cans(2) = "Sprite"
Cans(3) = "Mountain Dew"
Cans(4) = "Fanta"
Cans(5) = "Coca Cola"
Cans(6) = "Coke Diet"
Cans(7) = "Coke Vanilla"
End Sub
Private Sub ButtonPepsi_Click(sender As System.Object, e As System.EventArgs) Handles ButtonPepsi.Click
If money >= 0.8 Then
money = money - 0.8
TextBoxItem.TextAlign = HorizontalAlignment.Center
TextBoxItem.Text = "You brought a " & Cans(0)
TextboxCredit.Text = "£" & money
End If
End Sub
Every time I click the button to buy a pepsi, it just says in the textbox "You bought a " and it should say "Pepsi" but it does not work. Anybody got any ideas?
VB.NET has many methods of starting your application. Which one is used can be set in the project properties. The most common ones are:
Sub Main: Here, a sub Main in a module is called. Then, it's the sub's responsibility to start forms that should be shown.
Start Form: This is probably the option you are using. A specific form is opened and shown to the user. No Sub Main is executed.
How do you solve your problem? If you want to initialize the array when the window is opened, just use the Form.Load event for that:
Public Sub Form_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Cans(0) = "Pepsi"
Cans(1) = "Pepsi MAX"
...
End Sub
Main is never called, that's why your array elements are all empty string. I think you are mixing console and windows applications. You can place a call to Main in Sub New, after InitializeComponent. Or better, move all that code after InitializeComponent, to avoid confusion.
Or just declare your Cans array like this:
Dim Cans() As String = {"Pepsi", ..., "Coke Vanilla"}
Then you don't need Main at all.
Try this,
Private Sub ButtonPepsi_Click(sender As System.Object, e As System.EventArgs) Handles ButtonPepsi.Click
Main()
If money >= 0.8 Then
money = money - 0.8
TextBoxItem.TextAlign = HorizontalAlignment.Center
TextBoxItem.Text = "You brought a " & Cans(0)
TextboxCredit.Text = "£" & money
End If
End Sub
Got a small problem. I don't know how to search one array so I can pull that same array number from the other 2 arrays. I know how to test for a lot of stuff so that won't be a problem.
The end result on this project is the user will place the amount they are willing to pay for a make of the car and the page will display the data. HOWEVER I don't know how to search the carArray() to find the index number and use that index number to find the other stuff. I did find something that did this (somewhat) earlier but I don't know how to modify it for me to keep that index number as a int and use it to search and display the other arrays.
I will need this in future projects later.
Public Class paymentPage
Private Sub car_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles car.TextChanged
End Sub
Private Sub price_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles price.TextChanged
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim carArray() As String = {"Ford", "Chevy", "Mazda"}
Dim sellAmount() As Decimal = {32700, 35625, 24780}
Dim leaseAmount() As Decimal = {425, 505, 385}
End Sub
End Class
Why not make this a class object? Easier to reuse later.
Public Class Car
Public Property Make As String
Public Property Value As Double
Public Property Lease As Double
End Class
Then make a collection of them:
Private cars As New List(Of Car)
cars.Add(New Car With {.Make = "Ford", .Value = 32700, .Lease = 425})
cars.Add(New Car With {.Make = "Chevy", .Value = 35625, .Lease = 505})
cars.Add(New Car With {.Make = "Mazda", .Value = 24780, .Lease = 385})
For your requirements:
Private Function getIndexByName(make As string) As Integer
Dim result As Integer = -1
For i As Integer = 0 To carArray.Length -1
If carArray(i) = make Then
result = i
Exit for
End If
Next
Return Result
End Function
Usage:
Dim mazdalease = leaseAmt(getIndexByName("Mazda"))
Dim cars as new List(Of Car)({car1,car2,car3})
Dim indexOfCar2 = Array.IndexOf(cars.ToArray(),car2)
Since its dirt simple to convert to an array then you can use the built in function. Keep in mind that you need to override GetHash and Equals to get this to work properly.