Null Reference Exception was Unhandled - vb.net

This is a very simple code. I am just beginning to use vb. Im making a game where you try to solve a puzzle in the least amount of time and least amount of clicks. Every time I debug the program, it highlights the Clicks and FinalTime and says Null Reference Exception was Unhandled. I declared Clicks and FinalTime globally
Public Class Form1
Dim Clicks As Integer = 0 'The variable that counts the number of times you clicked
Dim Time As Integer 'The vairable that holds the time
Dim TimeMin As Integer 'The variable that holds the minutes
Dim TimeSec As Integer 'The variable that holds the seconds
Dim FinalTime As String 'The variable that holds the final time (minutes and seconds)
Dim NumArray() As Integer
Dim NumArray1() As String
Private Sub Times
Time = Time + 1
TimeSec = TimeSec + 1
TimeMin = Convert.ToInt32(TimeSec \ 60)
If Time >= 60 Then
Time = 0
End If
FinalTime = TimeMin & " min " & Time & " seconds"
lblTime.Text = FinalTime
End Sub
Private Sub Record(ByVal NumArray() As Integer, ByVal NumArray1() As String)
For i As Integer = 0 To 1000
NumArray(i) = Clicks 'Problem is here
i = +1
Array.Sort(NumArray)
Next i
lblRecordClicks.Text = NumArray(0) & " Clicks"
For k As Integer = 0 To 1000
NumArray1(k) = FinalTime 'Problem is here
k = +1
Array.Sort(NumArray1)
Next k
lblRecordTime.Text = NumArray1(0)
End Sub

Rule #1. Strings in VB.NET are not the same as Strings in VB6.
In VB6 you can say
Dim text as String
and you would have text = "" initialized
In VB.NET you need
Dim text as String = vbNullString
or
Dim text as New String
The same applies to arrays of string (or any other array)
Dim arr as String() ' This makes arr = Nothing
arr = New String(10) { } ' This allocates an array with 11 items (0..10)
or
Dim arr as String() = New String(10) {}
or
Dim arr() As String = New String(10) {}
or
Dim arr() = New String(10) {}
or
Dim arr = New String(10) {}
See related: Classes and arrays how to initialize?

Related

My output is giving the numbers instead of asterisks, how do I show asterisks there instead?

Output I am getting -
What I am trying to get -
Hi, I am trying to create a program that takes calories in daily and charts them in a daily summary and a weekly summary but with asterisks, but I cant figure out how to make asterisks show as in place of the numbers, like " ***** " instead of 5. I included pictures of the output I am getting as well as what i am supposed to get as well as the code I have so far. Any help would be appreciated.
Public Class frmA9
'Global Variables
Dim printedHeaderDaily As Boolean = False
'Global Constaints
Const FILL_SPACE As Integer = 2
Const DAY_HEADING As String = "Day"
Const TIME_HEADING As String = "Time"
Const TOTAL_HEADING As String = " "
Const TIME_LABEL_1 As String = " 5-11 AM"
Const TIME_LABEL_2 As String = " 11-5 PM"
Const TIME_LABEL_3 As String = " 5-11 PM"
Const TIME_LABEL_4 As String = " 11-5 AM"
Const TIME_RANGE_1 As Integer = 1
Const TIME_RANGE_2 As Integer = 2
Const TIME_RANGE_3 As Integer = 3
Const TIME_RANGE_4 As Integer = 4
Const TIME_LEN As Integer = 7
Const TIME_IDX_START_1 As Integer = 5
Const TIME_IDX_START_2 As Integer = 14
Const TIME_IDX_START_3 As Integer = 23
Const TIME_IDX_START_4 As Integer = 32
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAddtoSummary.Click
Dim existingIdx As Integer = -1
Dim dayformat As String = "{0,3}" & Space(FILL_SPACE) &
"{1,7:N0}" & Space(FILL_SPACE) &
"{2,7:N0}" & Space(FILL_SPACE) &
"{3,7:N0}" & Space(FILL_SPACE) &
"{4,7:N0}"
'Is header needed
If Not printedHeaderDaily Then
'Insert header
lstDailySummary.Items.Add(String.Format(dayformat,
DAY_HEADING,
TIME_LABEL_1,
TIME_LABEL_2,
TIME_LABEL_3,
TIME_LABEL_4))
'Avoid repeating header
printedHeaderDaily = True
End If
'Search for day in existing list
existingIdx = lstDailySummary.FindString(determineDay)
'Replace existing or insert new
If existingIdx > -1 Then
'Replace
lstDailySummary.Items.Item(existingIdx) = String.Format(dayformat,
determineDay,
CInt(txt5AM.Text),
CInt(txt11AM.Text),
CInt(txt5PM.Text),
CInt(txt11PM.Text))
Else
'New
lstDailySummary.Items.Add(String.Format(dayformat,
determineDay,
CInt(txt5AM.Text),
CInt(txt11AM.Text),
CInt(txt5PM.Text),
CInt(txt11PM.Text)))
End If
'Display weekly total
updateWeeklyTotatl()
End Sub
Sub updateWeeklyTotatl()
Dim totalTimeOne As Long
Dim totalTimeTwo As Long
Dim totalTimeThree As Long
Dim totalTimeFour As Long
Dim totalWeek As Long
Dim headerformat As String = "{0,-10:S}{1,6:S}"
Dim detailFormat As String = "{0,-10}{1,6:N0}"
'Remove existing data
lstWeekSummary.Items.Clear()
'Sum individual time ranges
totalTimeOne = sumCalForTime(TIME_RANGE_1)
totalTimeTwo = sumCalForTime(TIME_RANGE_2)
totalTimeThree = sumCalForTime(TIME_RANGE_3)
totalTimeFour = sumCalForTime(TIME_RANGE_4)
'Sum entire week
totalWeek = totalTimeOne + totalTimeTwo + totalTimeThree + totalTimeFour
'Insert header row
lstWeekSummary.Items.Add(String.Format(headerformat, TIME_HEADING, TOTAL_HEADING))
'Add bar for each time range
lstWeekSummary.Items.Add(String.Format(detailFormat, TIME_LABEL_1, totalTimeOne))
lstWeekSummary.Items.Add(String.Format(detailFormat, TIME_LABEL_2, totalTimeTwo))
lstWeekSummary.Items.Add(String.Format(detailFormat, TIME_LABEL_3, totalTimeThree))
lstWeekSummary.Items.Add(String.Format(detailFormat, TIME_LABEL_4, totalTimeFour))
End Sub
Function determineDay() As String
Dim selectedDay As String
'Identify the selected Day
If rdbSun.Checked Then
selectedDay = "Sun"
ElseIf rdbMon.Checked Then
selectedDay = "Mon"
ElseIf rdbTues.Checked Then
selectedDay = "Tues"
ElseIf rdbWed.Checked Then
selectedDay = "Wed"
ElseIf rdbThurs.Checked Then
selectedDay = "Thurs"
ElseIf rdbFri.Checked Then
selectedDay = "Fri"
ElseIf rdbSat.Checked Then
selectedDay = "Sat"
End If
Return selectedDay
End Function
Function determineStartIndex(ByVal timeRange As Integer) As Integer
Dim startIndex As Integer
'Identify start index of given time range
Select Case timeRange
Case TIME_RANGE_1
startIndex = TIME_IDX_START_1
Case TIME_RANGE_2
startIndex = TIME_IDX_START_2
Case TIME_RANGE_3
startIndex = TIME_IDX_START_3
Case TIME_RANGE_4
startIndex = TIME_IDX_START_4
End Select
Return startIndex
End Function
Function sumCalForTime(ByVal timeRange As Integer) As Long
Dim CalSum As Long
Dim startIndex As Integer
'Find index of first number in given time range
startIndex = determineStartIndex(timeRange)
'Iterate through the daily summary
'Sum all water consumed in the given range
For idxRow As Integer = 1 To lstDailySummary.Items.Count - 1
CalSum += CLng(lstDailySummary.Items.Item(idxRow).ToString.Substring(startIndex, TIME_LEN))
Next
Return CalSum
End Function
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
'Remove daily entries
lstDailySummary.Items.Clear()
'Remove weekly summary
lstWeekSummary.Items.Clear()
'Ensure daily header is printed after each entry
printedHeaderDaily = False
End Sub
End Class
You can use the String class constructor overload that accept two parameters: character and repeat times:
New String("*"c, 5) ' = *****
So, Change the following lines:
'Add bar for each time range
lstWeekSummary.Items.Add(String.Format(detailFormat, TIME_LABEL_1, totalTimeOne))
lstWeekSummary.Items.Add(String.Format(detailFormat, TIME_LABEL_2, totalTimeTwo))
lstWeekSummary.Items.Add(String.Format(detailFormat, TIME_LABEL_3, totalTimeThree))
lstWeekSummary.Items.Add(String.Format(detailFormat, TIME_LABEL_4, totalTimeFour))
To:
'Add bar for each time range
lstWeekSummary.Items.Add(String.Format(detailFormat, TIME_LABEL_1, New String("*"c, totalTimeOne)))
lstWeekSummary.Items.Add(String.Format(detailFormat, TIME_LABEL_2, New String("*"c,totalTimeTwo)))
lstWeekSummary.Items.Add(String.Format(detailFormat, TIME_LABEL_3, New String("*"c,totalTimeThree)))
lstWeekSummary.Items.Add(String.Format(detailFormat, TIME_LABEL_4, New String("*"c,totalTimeFour)))
Danielle,
It would be easy to convert your number to a series of asterisk.
New String("*"c, totalTimeOne)
I don't think that will solve your issue. You are totaling the calories for a day and will come up with a number (e.g. for 5-11AM the total is 2600). You then have a series of headers for calories. Your max is 18310, and 2600 is 14% of the total. Let's say you have a max of 200 characters in your list box. You would multiply .14*200 which = 28. So then you would print out 28 asterisks.
New String("*"c, 28)
This could look something like this:
Sub updateWeeklyTotatl()
Dim totalTimeOne As Long
Dim totalTimeTwo As Long
Dim totalTimeThree As Long
Dim totalTimeFour As Long
Dim totalWeek As Long
Dim totalAsterisk As Long = 200 'set this to your total number of Asterisks possible
Dim maxWeekSummary As Long = 18310 'set this to the max number in chart
Dim headerformat As String = "{0,-10:S}{1,6:S}"
Dim detailFormat As String = "{0,-10}{1,6:N0}"
'Remove existing data
lstWeekSummary.Items.Clear()
'Sum individual time ranges
totalTimeOne = sumCalForTime(TIME_RANGE_1)
totalTimeTwo = sumCalForTime(TIME_RANGE_2)
totalTimeThree = sumCalForTime(TIME_RANGE_3)
totalTimeFour = sumCalForTime(TIME_RANGE_4)
'Sum entire week
totalWeek = totalTimeOne + totalTimeTwo + totalTimeThree + totalTimeFour
'Insert header row
lstWeekSummary.Items.Add(String.Format(headerformat, TIME_HEADING, TOTAL_HEADING))
'Add bar for each time range
' this formula will calculate the number of asterisks to show CInt((totalTimeOne / maxWeekSummary) * totalAsterisk)
lstWeekSummary.Items.Add(String.Format(detailFormat, TIME_LABEL_1, New String("*"c, CInt((totalTimeOne / maxWeekSummary) * totalAsterisk))))
lstWeekSummary.Items.Add(String.Format(detailFormat, TIME_LABEL_2, New String("*"c, CInt((totalTimeTwo / maxWeekSummary) * totalAsterisk))))
lstWeekSummary.Items.Add(String.Format(detailFormat, TIME_LABEL_3, New String("*"c, CInt((totalTimeThree / maxWeekSummary) * totalAsterisk))))
lstWeekSummary.Items.Add(String.Format(detailFormat, TIME_LABEL_4, New String("*"c, CInt((totalTimeFour / maxWeekSummary) * totalAsterisk))))
End Sub

How to indentify the positions that a word occurs in a given text?

I am developing a program where you can input a sentence and then search for a word. The program will then tell you at which positions this word occurs. I have written some code but do not know how to continue.
Module Module1
Sub Main()
Dim Sentence As String
Dim SentenceLength As Integer
Dim L As Integer = 0
Dim LotsofText As String = Console.ReadLine
Console.WriteLine("Enter your word ") : Sentence = Console.ReadLine
For L = 1 To LotsofText.Length
If (Mid(LotsofText, L, 1)) = " " Then
End If
L = L + 1
Dim TextCounter As Integer = 0
Dim MainWord As String = Sentence
Dim CountChar As String = " "
Do While InStr(MainWord, CountChar) > 0
MainWord = Mid(MainWord, 1 + InStr(MainWord, CountChar), Len(MainWord))
TextCounter = TextCounter + 1
'Text = TextCounter + 2
' Console.WriteLine(Text)
Loop
Console.WriteLine(TextCounter)
Console.Write("Press Enter to Exit")
Console.ReadLine()
End Sub
End Module
Transform this piece of code from C# to Visual Basic. match.Index will indicate the position of the given word.
var rx = new Regex("your");
foreach (Match match in rx.Matches("This is your text! This is your text!"))
{
int i = match.Index;
}
To find only words and not sub-strings (for example to ignore "cat" in "catty"):
Dim LotsofText = "catty cat"
Dim Sentence = "cat"
Dim pattern = "\b" & Regex.Escape(Sentence) & "\b"
Dim matches = Regex.Matches(LotsofText, pattern)
For Each m As Match In matches
Debug.Print(m.Index & "") ' 6
Next
If you want to find sub-strings too, you can remove the "\b" parts.
If you add this function to your code:
Public Function GetIndexes(ByVal SearchWithinThis As String, ByVal SearchForThis As String) As List(Of Integer)
Dim Result As New List(Of Integer)
Dim i As Integer = SearchWithinThis.IndexOf(SearchForThis)
While (i <> -1)
Result.Add(i)
i = SearchWithinThis.IndexOf(SearchForThis, i + 1)
End While
Return Result
End Function
And call the function in your code:
Dim Indexes as list(of Integer) = GetIndexes(LotsofText, Sentence)
Now GetIndexes will find all indexes of the word you are searching for within the sentence and put them in the list Indexes.

Listbox formatting VB

I would like to format my listbox so that the output becomes something like this.
This is method, not in the main form tho:
Public Function GetSeatInfoStrings(ByVal choice As DisplayOptions,
ByRef strSeatInfoStrings As String()) As Integer
Dim count As Integer = GetNumOfSeats(choice)
If (count <= 0) Then
Return 0
End If
strSeatInfoStrings = New String(count - 1) {}
Dim StrReservation As String = ""
strSeatInfoStrings = New String(count - 1) {}
Dim i As Integer = 0 'counter for return array
'is the element corresponding with the index empty
For index As Integer = 0 To m_totNumOfSeats - 1
Dim strName As String = ""
Dim reserved As Boolean = Not String.IsNullOrEmpty(m_nameList(index))
'if the criteria below are not met, skip to add info in the array
If (choice = DisplayOptions.AllSeats) Or
(reserved And choice = DisplayOptions.ReservedSeats) Or
((Not reserved) And (choice = DisplayOptions.VacantSeats)) Then
If (reserved) Then
StrReservation = "Reserved"
strName = m_nameList(index)
Else
StrReservation = "Vacant"
strName = "..........."
End If
strSeatInfoStrings(i) = String.Format("{0,4} {1,-8} {2, -20} {3,10:f2}",
index + 1, StrReservation, strName, m_priceList(index))
i += 1
End If
Next
Return count
End Function
I don't know how to format the listbox as the strSeatInfoStrings(i) in the main form.
My listbox
This is what I've done
Private Sub UpdateGUI()
'Clear the listbox and make it ready for new data.
ReservationList.Items.Clear()
'size of array is determined in the callee method
Dim seatInfoStrings As String() = Nothing
Dim calcOption As DisplayOptions = DirectCast(cmbDisplayOptions.SelectedIndex, DisplayOptions)
Dim count As Integer = m_seatMngr.GetSeatInfoStrings(calcOption, seatInfoStrings)
If count > 0 Then
ReservationList.Items.AddRange(seatInfoStrings)
Else
ReservationList.Items.Add("Nothing to display!")
End If
Found the error! I forgot to call the UpdateGUI() in the IntializeGUI().

A first chance exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll on a combat simulator

I have an issue trying to program a simple combat simulation for a project that I and another person is working on.
Module Module1
Dim Player_Vitality As Integer
Dim PlayerReiatsu As Integer
Dim PlayerZanjustu As Integer
Dim PlayerHakuda As Integer
Dim PlayerHoho As Integer
Dim PlayerKido As Integer
Dim PlayerAbility As Integer
Dim Player_Physical_Damage As Integer
Dim Player_Spirit_Damage As Integer
Dim Player_Critical_Chance As Integer
Dim Player_Critical_Damage As Integer
Sub Main()
Call Shuhei()
End Sub
Sub Shuhei()
Dim Shuhei_reiatsu As Integer
Dim Shuhei_Vitality_TurnStart As Integer
Dim Shuhei_Vitality_TurnEnd As Integer
Dim Attack As String
Dim Kido As Integer
Dim Sword As Integer
Dim Shuhei_Temp As Integer
PlayerZanjustu = 40
PlayerHakuda = 50
PlayerKido = 50
PlayerAbility = 75
Shuhei_reiatsu = 80
Kido = Player_Spirit_Damage
Sword = Player_Physical_Damage
'Player_Vitality = 100
Shuhei_Vitality_TurnStart = 1000
Console.WriteLine("FIGHT 1")
Console.ReadLine()
Do While Shuhei_Vitality_TurnStart > 0
Player_Physical_Damage = ((PlayerZanjustu + PlayerHakuda) - Shuhei_reiatsu)
Player_Spirit_Damage = ((PlayerKido + PlayerAbility) - Shuhei_reiatsu)
'Player_Critical_Chance = ((PlayerZanjustu + PlayerHoho) - Shuhei_reiatsu) / 100
'Player_Critical_Damage = (PlayerZanjustu + PlayerHakuda) * 10
Shuhei_Temp = Shuhei_Vitality_TurnStart
Console.WriteLine("Shuhei has " & Shuhei_Temp & "Hp")
Console.WriteLine("Which attack do you want to use?")
Attack = Console.ReadLine
If Attack = "Kido" Or Kido Then
Shuhei_Vitality_TurnEnd = ((Shuhei_Temp) - Player_Spirit_Damage)
ElseIf Attack = "Sword" Or Sword Then
Shuhei_Vitality_TurnEnd = Shuhei_Temp - Player_Physical_Damage
Else
Console.WriteLine("Please choose an attack")
End If
Shuhei_Vitality_TurnEnd = Shuhei_Vitality_TurnStart
If Shuhei_Vitality_TurnStart <= 0 Then
Call FightEnd()
End If
Loop
Console.ReadKey()
End Sub
Sub FightEnd()
Console.WriteLine("Shuhei has been defeated")
Console.ReadKey()
End Sub
This is all copied down to the point in a new sub where there is deactivated junk with no purpose as of yet, so I doubt that is the issue, it is just the skeleton of the combat code but with ' in front to disable it. Then at the bottom the End Module command
In your IF Statement Attack could really never be "Kido" or Kido. You are comparing a string to a string or a string to an integer and that is likely your issue. Try converting Kido the variable to a string and that might supress the error.
Pseudo code:
If Attack = "Kido" Or Kido.ToString

How do I create a loop statement that finds the specific amount of characters in a string?

Beginner here, bear with me, I apologize in advance for any mistakes.
It's some homework i'm having a bit of trouble going about.
Overall goal: outputting the specific amount of characters in a string using a loop statement. Example being, user wants to find how many "I" is in "Why did the chicken cross the road?", the answer should be 2.
1) The form/gui has 1 MultiLine textbox and 1 button titled "Search"
2) User enters/copys/pastes text into the Textbox clicks "Search" button
3) Search button opens an InputBox where the user will type in what character(s) they want to search for in the Textbox then presses "Ok"
4) (where I really need help) Using a Loop Statement, The program searches and counts the amount of times the text entered into the Inputbox, appears in the text inside the MultiLine Textbox, then, displays the amount of times the character showed up in a "messagebox.show"
All I have so far
Private Sub Search_btn_Click(sender As System.Object, e As System.EventArgs) Handles Search_btn.Click
Dim counterInt As Integer = 0
Dim charInputStr As String
charInputStr = CStr(InputBox("Enter Search Characters", "Search"))
I would use String.IndexOf(string, int) method to get that. Simple example of concept:
Dim input As String = "Test input string for Test and Testing the Test"
Dim search As String = "Test"
Dim count As Integer = -1
Dim index As Integer = 0
Do
index = input.IndexOf(search, index) + 1
count += 1
Loop While index > 0
count is initialized with -1 because of do-while loop usage - it will be set to 0 even if there is no pattern occurrence in input string.
Try this Code
Dim input As String = "Test input string for Test and Testing the Test"
Dim search() As String = {"Te"}
MsgBox(input.Split(input.Split(search, StringSplitOptions.None), StringSplitOptions.RemoveEmptyEntries).Count)
Concept: Increment the count until the input containing the particular search string. If it contains the search string then replace the first occurance with string.empty (In String.contains() , the search starts from its first index, that is 0)
Dim input As String = "Test input string for Test and Testing the Test"
Dim search As String = "T"
Dim count As Integer = 0
While input.Contains(search) : input = New Regex(search).Replace(input, String.Empty, 1) : count += 1 : End While
MsgBox(count)
Edit:
Another solution:
Dim Input As String = "Test input string for Test and Testing the Test"
Dim Search As String = "Test"
MsgBox((Input.Length - Input.Replace(Search, String.Empty).Length) / Search.Length)
try this code.... untested but i know my vb :)
Function lol(ByVal YourLine As String, ByVal YourSearch As String)
Dim num As Integer = 0
Dim y = YourLine.ToCharArray
Dim z = y.Count
Dim x = 0
Do
Dim l = y(x)
If l = YourSearch Then
num = num + 1
End If
x = x + 1
Loop While x < z
Return num
End Function
Its a function that uses its own counter... for every character in the string it will check if that character is one that you have set (YourSearch) and then it will return the number of items that it found. so in your case it would return 2 because there are two i's in your line.
Hope this helps!
EDIT:
This only works if you are searching for individual Characters not words
You can try with something like this:
Dim sText As String = TextBox1.Text
Dim searchChars() As Char = New Char() {"i"c, "a"c, "x"c}
Dim index, iCont As Integer
index = sText.IndexOfAny(searchChars)
While index >= 0 Then
iCont += 1
index = sText.IndexOfAny(searchChars, index + 1)
End While
Messagebox.Show("Characters found " & iCont & " times in text")
If you want to search for words and the times each one is appearing try this:
Dim text As String = TextBox1.Text
Dim wordsToSearch() As String = New String() {"Hello", "World", "foo"}
Dim words As New List(Of String)()
Dim findings As Dictionary(Of String, List(Of Integer))
'Dividing into words
words.AddRange(text.Split(New String() {" ", Environment.NewLine()}, StringSplitOptions.RemoveEmptyEntries))
findings = SearchWords(words, wordsToSearch)
Console.WriteLine("Number of 'foo': " & findings("foo").Count)
With this function used:
Private Function SearchWords(ByVal allWords As List(Of String), ByVal wordsToSearch() As String) As Dictionary(Of String, List(Of Integer))
Dim dResult As New Dictionary(Of String, List(Of Integer))()
Dim i As Integer = 0
For Each s As String In wordsToSearch
dResult.Add(s, New List(Of Integer))
While i >= 0 AndAlso i < allWords.Count
i = allWords.IndexOf(s, i)
If i >= 0 Then dResult(s).Add(i)
i += 1
End While
Next
Return dResult
End Function
You will have not only the number of occurances, but the index positions in the file, grouped easily in a Dictionary.