Visual Basic - How to concatenate a string in a while loop - vb.net

I've been working on a homework problem for a few hours now and cannot for the life of me figure out how to get it to work.
The premise of the program is:
-User inputs number
-Display a multiplication table from 1-9 of that users number
if they entered 4 I need to show
1 * 4 = 4
2 * 4 = 8
.
.
.
9 * 4 = 36
Here is what I (unsuccessfully) have for my loop so far:
Dim userNum As Integer = numInputTextBox.Text
Dim tableDisplay As String
Dim i As Integer = 1
Do While i <= 9
tableDisplay = userNum * i
tableTextBox.Text = tableDisplay
i += 1
Loop
(tableTextBox is where the output will be stored)
The only output I get is the result of the last iteration of the loop so if I entered 7, the output I get is 63 (7 * 9)
I'm unsure how to continually add to a string and output it to the textbox while in a loop.
Any and all help is greatly appreciated. My apologies for the sloppy formatting.

Here is an idea of what I am talking about in my comment:
Dim userNum As Integer = numInputTextBox.Text
Dim tableDisplay As String
Dim i As Integer = 1
Do While i <= 9
tableDisplay = userNum & " * " & i & " = " & userNum * i & vbLf
i += 1
Loop
tableTextBox.Text = tableDisplay
Although I wouldn't use a while loop in this instance, I would use a for next like so:
Dim userNum As Integer = numInputTextBox.Text
Dim tableDisplay As String
Dim i As Integer
For i = 1 To 9
tableDisplay = userNum & " * " & i & " = " & userNum * i & vbLf
Next
tableTextBox.Text = tableDisplay

Related

VB - comparing numbers in two labels

I'm doing a school project in Visual Basic (using visual studio 2015) and i'm kinda stuck.
My goal is to create a lottery, where player chooses 6 numbers from checkboxes, then he generates six random numbers (1 - 49) and finally, those two sets should be compared and needed result is the number of correctly guessed numbers.
I have both results (guessed numbers, generated numbers) saved in two different labels.
The checkboxes itself are genereted like this:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lev = 20
tt = 0
For j = 1 To 50
tt = tt + 1
n = n + 1
box(j) = New CheckBox
box(j).Name = "box(" & Str(j) & ")"
If n = 11 Then lev = lev + 110 : n = 1 : tt = 1
box(j).Left = lev
box(j).Parent = Me
box(j).Top = tt * 20
box(j).Tag = j
box(j).Text = j
box(j).Visible = True
Next
box(50).Enabled = False
End Sub
First label (guessed numbers) is filled this way (i'm not posting whole code)
For j = 1 To 50
If box(j).Checked = True Then Label9.Text = Label9.Text + " " + box(j).Text
Next
and the second one (generated numbers) like this:
Do
rn = rg.Next(1, 50)
If Not r.Contains(rn) Then
r.Add(rn)
End If
Loop Until r.Count = 6
Label1.Text = r(0).ToString + " " + r(1).ToString + " " + r(2).ToString + " " + r(3).ToString + " " + r(4).ToString + " " + r(5).ToString
any idea how to compare numbers stored in those labels and get the result (number of correctly guessed numbers).
thanks in advance
You can compare numbers in the labels by splitting the Text properties of the labels into arrays of strings and converting them to integer arrays. First though there is a tiny problem with your code that adds the guessed numbers to the label.
For j = 1 To 50
If box(j).Checked = True Then Label9.Text = Label9.Text + " " + box(j).Text
Next
The " " should be moved to the end of the line because at the moment, the label will always start with a space and that messes with the function below. So you should have -
For j = 1 To 50
If box(j).Checked = True Then Label9.Text = Label9.Text + box(j).Text + " "
Next
Ok. The function below splits the two text labels into their own array and loops through the guesses and checks if any number is contained in the generated numbers. It then returns the number of matches.
Private Function ComparePicks() As Integer
Dim numbersMatched As Integer
Dim picks(5) As Integer
Dim generatedNumbers(5) As Integer
For i As Integer = 0 To 5
picks(i) = CInt(Split(Label9.Text, " "c)(i))
Next
For i As Integer = 0 To 5
generatedNumbers(i) = CInt(Split(Label1.Text, " "c)(i))
Next
For i As Integer = 0 To 5
If generatedNumbers.Contains(picks(i)) Then
numbersMatched += 1
End If
Next
Return numbersMatched
End Function

Working out a basic score from integer values

I'm trying to work out a basic % value by gathering values together:
For Each M As Match In matchFound
lamdaFix2 = M.Groups(1).Value
lamdaFix3 = M.Groups(2).Value
Application.DoEvents()
Dim lv As ListViewItem = formMozCheck.listViewMoz.Items.Add(lamdaFix1)
lv.UseItemStyleForSubItems = False
lv.SubItems.Add(Math.Round(Double.Parse(lamdaFix2)).ToString())
lv.SubItems.Add(Math.Round(Double.Parse(lamdaFix3)).ToString())
lv.SubItems.Add("-")
lv.SubItems.Add("-")
lv.SubItems.Add(itm.SubItems(8).Text)
Dim srVal As Integer
If (itm.SubItems(9).Text = "") Then
srVal = 0
Else
srVal = CInt(itm.SubItems(9).Text)
End If
lv.SubItems.Add(srVal.ToString())
' work out a score
Dim overAllScore As Integer
' TODO: basic score
overAllScore = CInt(CInt(CDbl(Math.Round(Double.Parse(lamdaFix2)).ToString()) & CDbl(Math.Round(Double.Parse(lamdaFix3)).ToString()) & CDbl(itm.SubItems(8).Text) & Val(srVal)) * 100)
lv.SubItems.Add(CLng(overAllScore) & "%").ForeColor = Color.DarkGreen
itm.Checked = False
Next
These values:
lv.SubItems.Add(Math.Round(Double.Parse(lamdaFix2)).ToString())
lv.SubItems.Add(Math.Round(Double.Parse(lamdaFix3)).ToString())
Are values between 0 - 100
And these ones:
itm.SubItems(8).Text
itm.SubItems(9).Text
Are values between 1 - 10
I have been racking the brains to see what the best way to add these values up and give a basic percentage, my attempt:
overAllScore = CInt(CInt(CDbl(Math.Round(Double.Parse(lamdaFix2)).ToString()) & CDbl(Math.Round(Double.Parse(lamdaFix3)).ToString()) & CDbl(itm.SubItems(8).Text) & Val(srVal)) * 100)
Just adds all values like 234524 rather than the total value of 23+45+2+4
i'm probably over complicating this lol
i tagged it as both vb and c# as i though the logic would be the same ;)
thanks for any help guys!
Graham
You should use "+" instead of "&":
overAllScore = CInt(CInt(CDbl(Math.Round(Double.Parse(lamdaFix2)).ToString()) + CDbl(Math.Round(Double.Parse(lamdaFix3)).ToString()) + CDbl(itm.SubItems(8).Text) + Val(srVal)) * 100)

How to count the number of spaces and characters in vb.net?

I want to count the number of spaces and characters inputted in a textbox field.
Example
textbox1.text - " 1 2 3 4 5 6 7 a b c"
I want to count the number of spaces and the characters
Then the result must be..
Dim spaces as integer, char as integer
spaces = 10 , char = 10
Dim spaceCount, lettercount As Integer
spaceCount= 0
lettercount = 0
Dim s As String = " 1 2 3 4 5 6 7 a b c"
For Each c As Char In s
If c = " " Then
spaceCount+= 1
Else
lettercount += 1
End If
Next
MsgBox(charcount)
MsgBox(lettercount)
For Each will iterate each character within the string then it will check whether c is a space or not. if it is a space then increment the spaceCount else increment the lettrtCount
You can do as you want in a sort way.
Try it
Dim count As Integer = 0
textbox1.text = " 1 2 3 4 5 6 7 a b c"
count = textbox1.text.Split(" ").Length -1
Dim longstring As String = "aab c d e"
Dim TotalLength As Integer = longstring.Length
Dim TotalSpaces() As String = Split(longstring, " "
Dim TotalChars As Integer = TotalLength - (TotalSpaces.Length - 1)

Converting RGB value into integers

I'm making an app with a color dropper tool on it using g.CopyFromScreen(screenpoint, Point.Empty, Bmp2.Size) (the dropper tool works currently), once I have the dropper values I want to convert the RBG values into individual integers.
The values that i'm converting are in this format
Color [A=255, R=240, G=240, B=240]
which needs to be in four different integers
My code is giving me odd results and I'm lost now
My code:
Dim text1Conv As String
text1Conv = TextBox1.Text
Dim myChars() As Char = text1Conv.ToCharArray()
For Each ch As Char In myChars
If Char.IsDigit(ch) And Not ch = " " And Not ch = "," And Not count > 2 Then
color1Conv = color1Conv + ch
TextBox2.Text = TextBox2.Text + color1Conv 'test result
count = count + 1
ElseIf Char.IsDigit(ch) And Not ch = " " And Not ch = "," And count < 2 And Not count > 5 Then
color2Conv = color2Conv + ch
TextBox2.Text = TextBox2.Text + color2Conv 'test result
count = count + 1
ElseIf Char.IsDigit(ch) And Not ch = " " And Not ch = "," And count < 5 And Not count > 8 Then
color3Conv = color3Conv + ch
TextBox2.Text = TextBox2.Text + color3Conv 'test result
count = count + 1
ElseIf Char.IsDigit(ch) And Not ch = " " And Not ch = "," And count < 8 And Not count > 11 Then
color4Conv = color4Conv + ch
TextBox2.Text = TextBox2.Text + color4Conv 'test result
count = count + 1
End If
Next
results: 225 255 118 112 122
results: 225 255 116 772 721
probably an easy one but I can't see it
Using regular expressions:
I used "[A=255, R=241, G=24, B=2]" as a test string and split it into four integers.
Dim a as Integer, r as Integer, g as Integer, b as Integer
Dim s as String = "[A=255, R=241, G=24, B=2]"
Dim mc as MatchCollection = System.Text.RegularExpressions.Regex.Matches( s, "(\d+)\D+(\d+)\D+(\d+)\D+(\d+)\D+", RegexOptions.None )
Integer.TryParse( mc(0).Groups(1).Value, a )
Integer.TryParse( mc(0).Groups(2).Value, r )
Integer.TryParse( mc(0).Groups(3).Value, g )
Integer.TryParse( mc(0).Groups(4).Value, b )
NOTE: it will have no problems with numbers being 1, 2, or any number of digits long.
You can use regular expressions:
Imports System.Text.RegularExpressions
Dim input As String = "Color [A=255, R=240, G=240, B=240]"
Dim re As New Regex("Color \[A=(\d+), R=(\d+), G=(\d+), B=(\d+)\]")
Dim m As Match = re.Match(input)
Dim integer1 As Integer = Convert.ToInt32(m.Groups(1).Value) '255
Dim integer2 As Integer = Convert.ToInt32(m.Groups(2).Value) '240
Dim integer3 As Integer = Convert.ToInt32(m.Groups(3).Value) '240
Dim integer4 As Integer = Convert.ToInt32(m.Groups(4).Value) '240

Calculate words value in vb.net

I have a textbox on a form where the user types some text. Each letter is assigned a different value like a = 1, b = 2, c = 3 and so forth. For example, if the user types "aa bb ccc" the output on a label should be like:
aa = 2
bb = 4
dd = 6
Total value is (12)
I was able to get the total value by looping through the textbox string, but how do I display the total for each word. This is what I have so far:
For letter_counter = 1 To word_length
letter = Mid(txtBox1.Text, letter_counter, 1)
If letter.ToUpper = "A" Then
letter_value = 1
End If
If letter.ToUpper = "B" Then
letter_value = 2
End If
If letter.ToUpper = "C" Then
letter_value = 3
End If
If letter.ToUpper = "D" Then
letter_value = 4
End If
If letter.ToUpper = "E" Then
letter_value = 5
End If
If letter.ToUpper = " " Then
letter_value = 0
End If
totalletter = totalletter + letter_value
Label1.Text = Label1.Text & letter_value & " "
txtBox2.Text = txtBox2.Text & letter_value & " "
Next letter_counter
This simple little routine should do the trick:
Private Sub CountLetters(Input As String)
Label1.Text = ""
Dim total As Integer = 0
Dim dicLetters As New Dictionary(Of Char, Integer)
dicLetters.Add("a"c, 1)
dicLetters.Add("b"c, 5)
dicLetters.Add("c"c, 7)
For Each word As String In Input.Split
Dim wordtotal As Integer = 0
For Each c As Char In word
wordtotal += dicLetters(Char.ToLower(c))
Next
total += wordtotal
'Display word totals here
Label1.Text += word.PadRight(12) + "=" + wordtotal.ToString.PadLeft(5) + vbNewLine
Next
'Display total here
Label1.Text += "Total".PadRight(12) + "=" + total.ToString.PadLeft(5)
End Sub
This should give you an idea:
Dim listOfWordValues As New List(Of Integer)
For letter_counter = 1 To word_length
letter = Mid(txtBox1.Text, letter_counter, 1)
If letter = " " Then
totalletter= totalletter + letter_value
listOfWordValues.Add(letter_value)
letter_value = 0
Else
letter_value += Asc(letter.ToUpper) - 64
End If
Next letter_counter
totalletter = totalletter + letter_value
If Not txtBox1.Text.EndsWith(" ") Then listOfWordValues.Add(letter_value)
txtBox2.Text = txtBox2.Text & string.Join(", ", listOFWordValues);
You can try something like this. Assuming txtBox1 is the string the user enters and " " (space) is the word delimiter:
Dim words As String() = txtBox1.Text.Split(New Char() {" "}, StringSplitOptions.RemoveEmptyEntries)
Dim totalValue As Integer = 0
Dim wordValue As Integer = 0
For Each word As String In words
wordValue = 0
For letter_counter = 1 To word.Length
Dim letter As String = Mid(txtBox1.Text, letter_counter, 1)
Select letter.ToUpper()
Case "A":
wordValue = wordValue + 1
Case "B":
wordValue = wordValue + 2
' And so on
End Select
Next
totalValue = toalValue + wordValue
Next
The above code first takes the entered text from the user and splits it on " " (space).
Next it sets two variables - one for the total value and one for the individual word values, and initializes them to 0.
The outer loop goes through each word in the array from the Split performed on the user entered text. At the start of this loop, it resets the wordValue counter to 0.
The inner loop goes through the current word, and totals up the values of the letter via a Select statement.
Once the inner loop exits, the total value for that word is added to the running totalValue, and the next word is evaluated.
At the end of these two loops you will have calculated the values for each word as well as the total for all the worlds.
The only thing not included in my sample is updating your label(s).
Try this ..
Dim s As String = TextBox1.Text
Dim c As String = "ABCDE"
Dim s0 As String
Dim totalletter As Integer
For x As Integer = 0 To s.Length - 1
s0 = s.Substring(x, 1).ToUpper
If c.Contains(s0) Then
totalletter += c.IndexOf(s0) + 1
End If
Next
MsgBox(totalletter)
I would solve this problem using a dictionary that maps each letter to a number.
Private Shared ReadOnly LetterValues As Dictionary(Of Char, Integer) = GetValues()
Private Shared Function GetValues() As IEnumerable(Of KeyValuePair(Of Char, Integer))
Dim values As New Dictionary(Of Char, Integer)
Dim value As Integer = 0
For Each letter As Char In "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
value += 1
values.Add(letter, value)
Next
Return values
End Function
Public Function CalculateValue(input As String) As Integer
Dim sum As Integer = 0
For Each letter As Char In input.ToUpperInvariant()
If LetterValues.ContainsKey(letter) Then
sum += LetterValues.Item(letter)
End If
Next
Return sum
End Function
Usage example:
Dim sum As Integer = 0
For Each segment As String In "aa bb ccc".Split()
Dim value = CalculateValue(segment)
Console.WriteLine("{0} = {1}", segment, value)
sum += value
Next
Console.WriteLine("Total value is {0}", sum)
' Output
' aa = 2
' bb = 4
' ccc = 9
' Total value is 15