VB.NET - Multiple user-input integers to arraylist - vb.net

I'm new to programming... I'm trying to code a very basic program so that 10 integers can be input by a user, and then averaged. I've considered using an ArrayList to store all the data, but once I use "Input" once I can't use it again.
What I'm supposed to do is take a basic averaging program like this:
Dim A, B, C, D, E, F, G, H, I, J As Integer
A = 10
B = 6
C = 17
...
...
...
J = 15
Dim K As Double
K = A + B + C + D + E + F + G + H + I + J
K /= 10
Console.WriteLine(K)
Console.ReadKey()
...and make it so that the user can input all of the variables.
Hopefully this problem is clear enough... anybody know what I can do?

I have included below and example with comments. Hopefull you will learn from the statements and understand how to loop with Do/Loop or For and how to use List(Of ) to store a variable amount of data.
Sub Main()
' Initialize variable for text input, and numeric value
Dim input As String, x As Double
' Initialize empty array of numbers
Dim array = New List(Of Double)()
Do
Console.Write("Enter a number or press [Enter] to Finish :")
' Read a number (as text)
input = Console.ReadLine()
' Check if input is a number
If (Double.TryParse(input, x)) Then
' If it is a number add it to list
array.Add(x)
ElseIf x.Length>0
' If not then display a message
Console.WriteLine("** Input Not Numeric **")
End If
' Continue until user presses enter
Loop Until input.Length = 0
Console.WriteLine("{0} Numbers Entered", array.Count)
' Calculate average from values
Dim average As Double = 0
For index As Integer = 1 To array.Count
average += array(index - 1)
Next
average /= array.Count
' Display results and wait for enter
Console.WriteLine("The Average Is {0}", average)
Console.Write("Press [Enter] to End")
Console.ReadLine()
End Sub

I would do things in steps. First your way.
Dim a, b, c, d As Integer
Console.Write("Type an integer: ")
a = Int32.Parse(Console.ReadLine())
Console.Write("Type an integer: ")
b = Int32.Parse(Console.ReadLine())
Console.Write("Type an integer: ")
c = Int32.Parse(Console.ReadLine())
Console.Write("Type an integer: ")
d = Int32.Parse(Console.ReadLine())
Console.WriteLine("The average is: " & ((a + b + c + d) / 4))
Console.ReadLine()
Then you convert the code to use a list
Dim v As New List(Of Integer)
Console.Write("Type an integer: ")
v.Add(Int32.Parse(Console.ReadLine()))
Console.Write("Type an integer: ")
v.Add(Int32.Parse(Console.ReadLine()))
Console.Write("Type an integer: ")
v.Add(Int32.Parse(Console.ReadLine()))
Console.Write("Type an integer: ")
v.Add(Int32.Parse(Console.ReadLine()))
Console.WriteLine("The average is: " & ((v(0) + v(1) + v(2) + v(3)) / 4))
Console.ReadLine()
Now that you are using a list, you can easely use a loop to remove duplicate code.
Dim v As New List(Of Integer)
Do While v.Count < 4
Console.Write("Type an integer: ")
v.Add(Int32.Parse(Console.ReadLine()))
Loop
Console.WriteLine("The average is: " & ((v(0) + v(1) + v(2) + v(3)) / 4))
Console.ReadLine()
After that you add error validation and use the built-in Average function.
Dim tempVal As Integer
Dim v As New List(Of Integer)
Do While v.Count < 4
Console.Write("Type an integer: ")
If Int32.TryParse(Console.ReadLine(), tempVal) Then
v.Add(tempVal)
Else
Console.WriteLine("Not a valid integer")
End If
Loop
Console.WriteLine("The average is: " & v.Average())
Console.ReadLine()

Related

Splitting string every 100 characters not working

I am having a problem where I just can't seem to get it to split or even display the message. The message variable is predefined in another part of my code and I have debugged to make sure that the value comes through. I am trying to get it so that every 100 characters it goes onto a new line and with every message it also goes onto a new line.
y = y - 13
messagearray.AddRange(Message.Split(ChrW(100)))
Dim k = messagearray.Count - 1
Dim messagefin As String
messagefin = ""
While k > -1
messagefin = messagefin + vbCrLf + messagearray(k)
k = k - 1
End While
k = 0
Label1.Text = Label1.Text & vbCrLf & messagefin
Label1.Location = New Point(5, 398 + y)
You can use regular expression. It will create the array of strings where every string contains 100 characters. If the amount of remained characters is less than 100, it will match all of them.
Dim input = New String("A", 310)
Dim mc = Regex.Matches(input, ".{1,100}")
For Each m As Match In mc
'// Do something
MsgBox(m.Value)
Next
You can use LINQ to do that.
When you do a Select you can get the index of the item by including a second parameter. Then group the characters by that index divided by the line length so, the first character has index 0, and 0 \ 100 = 0, all the way up to the hundredth char which has index 99: 99 \ 100 = 0. The next hundred chars have 100 \ 100 = 1 to 199 \ 100 = 1, and so on (\ is the integer division operator in VB.NET).
Dim message = New String("A"c, 100)
message &= New String("B"c, 100)
message &= New String("C"c, 99)
Dim lineLength = 100
Dim q = message.Select(Function(c, i) New With {.Char = c, .Idx = i}).
GroupBy(Function(a) a.Idx \ lineLength).
Select(Function(b) String.Join("", b.Select(Function(d) d.Char)))
TextBox1.AppendText(vbCrLf & String.Join(vbCrLf, q))
It is easy to see how to change the line length because it is in a variable with a meaningful name, for example I set it to 50 to get the output
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
You can use String.SubString to do that. Like this
Dim Message As String = "your message here"
Dim MessageList As New List (Of String)
For i As Integer = 0 To Message.Length Step 100
If (Message.Length < i + 100) Then
MessageList.Add(Message.SubString (i, Message.Length - i)
Exit For
Else
MessageList.Add(Message.SubString (i, 100))
End If
Next
Dim k = MessageList.Count - 1
...
Here is what your code produced with a bit of clean up. I ignored the new position of the label.
Private Sub OpCode()
Dim messagearray As New List(Of String) 'I guessed that messagearray was a List(Of T)
messagearray.AddRange(Message.Split(ChrW(100))) 'ChrW(100) is lowercase d
Dim k = messagearray.Count - 1
Dim messagefin As String
messagefin = ""
While k > -1
messagefin = messagefin + vbCrLf + messagearray(k)
k = k - 1
End While
k = 0 'Why reset k? It falls out of scope at End Sub
Label1.Text = Label1.Text & vbCrLf & messagefin
End Sub
I am not sure why you think that splitting a string by lowercase d would have anything to do with getting 100 characters. As you can see the code reversed the order of the list items. It also added a blank line between the existing text in the label (In this case Label1) and the new text.
To accomplish your goal, I first created a List(Of String) to store the chunks. The For loop starts at the beginning of the input string and keeps going to the end increasing by 10 on each iteration.
To avoid an index out of range which would happen at the end. Say, we only had 6 characters left from start index. If we tried to retrieve 10 characters we would have an index out of range.
At the end we join the elements of the string with the separated of new line.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
BreakInto10CharacterChunks("The quick brown fox jumped over the lazy dogs.")
End Sub
Private Sub BreakInto10CharacterChunks(input As String)
Dim output As New List(Of String)
Dim chunk As String
For StartIndex = 0 To input.Length Step 10
If StartIndex + 10 > input.Length Then
chunk = input.Substring(StartIndex, input.Length - StartIndex)
Else
chunk = input.Substring(StartIndex, 10)
End If
output.Add(chunk)
Next
Label1.Text &= vbCrLf & String.Join(vbCrLf, output)
End Sub
Be sure to look up String.SubString and String.Join to fully understand how these methods work.
https://learn.microsoft.com/en-us/dotnet/api/system.string.substring?view=netframework-4.8
and https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=netframework-4.8

Visual Basic loop sum of integers ^ 2 till user input. power of 2

I need help with one simple task:
Input an integer number n and output the sum: 1 + 2^2 + 3^2 + ... + n^2. Use input validation for n to be positive.
My code does not work and till now is:
Sub Main()
Dim inputNumber As Integer
Console.WriteLine("Please enter a positive number.")
inputNumber = Console.ReadLine()
If inputNumber <= 0 Then
Console.WriteLine("Please use only positive numbers > 0 !")
End If
Dim sum As Integer
Dim i As Integer = 1
For i = 1 To i <= inputNumber
sum = sum + (i * i)
i = i + 1
Next
Console.WriteLine(sum)
Console.ReadLine()
End Sub
Try these changes:
Dim inputNumber as Long ' not Integer. Also change sum, i.
...
inputNumber = CLng(Console.ReadLine) ' make it a number, not a string
...
Dim sum as Long ' yum
dim i as Long ' don't assign it here
for i = 1 to inputNumber ' don't use "<=" in a for loop
...
' i = i+1 ' Don't increment i within the loop, since the loop does that for you.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Input As Integer
Input = TextBox1.Text
Dim i As Integer
i = 0
Dim x As Integer
x = 0
Dim y As Integer
y = 0
For a = 1 To Input
y = Math.Pow(a, (Input - i))
x = Math.Pow(a, (Input - i)) + x
i = i + 1
Next
Label1.Text = x
End Sub

Calculate each letter and the total vb.net

I have the following function that takes input from txtbox1 and outputs the result in txtbox2. The main point is to substitute each letter with a specific numeric value, calculate the value of each word and then display the total of all words. Right now, this function is calculating always to 13. If I type aaa bbb cc for example, the result should be. How do I modify the function to do that?
aaa = 3
bbb = 15
cc = 14
Total = 32
Private Sub CountLetters(Input As String)
Dim total As Integer = 0
Dim dicLetters As New Dictionary(Of Char, Integer)
dicLetters.Add("a", 1)
dicLetters.Add("b", 5)
dicLetters.Add("c", 7)
For Each word As String In Input.Split
Dim wordtotal As Integer = 0
For Each cc As KeyValuePair(Of Char, Integer) In dicLetters
wordtotal += cc.Value
Next
total += wordtotal
'Display word totals here
txtBox2.Text += word.PadRight(12) + "=" + _
wordtotal.ToString.PadLeft(5) + vbNewLine
Next
'Display total here
txtBox2.Text += "Total".PadRight(12) + "=" + total.ToString.PadLeft(5)
End Sub
As logixologist indicated, the issue is your looping through the dictionary and summing up the values of the keys, not the values of the words.
If you have a value for each letter, a Dictionary is a good way to go (if it's only a few letters than a Select would be fine as well).
Below is some code that will get the result you're looking for:
Dim total As Integer = 0
Dim wordTotal AS Integer
Dim dicLetters As New Dictionary(Of Char, Integer)
dicLetters.Add("a", 1)
dicLetters.Add("b", 5)
dicLetters.Add("c", 7)
' charValue will be used to hold the result of the TryGetValue below
Dim charValue As Integer
For Each word As String In Input.Split(New Char() { " " })
wordTotal = 0
' Loop through the word
For Each character As Char in word
wordTotal += If(dicLetters.TryGetValue(character, charValue) = _
True, dicLetters(character), 0)
Next
total += wordTotal
txtBox2.Text += word.PadRight(12) + " = " + _
wordTotal.ToString().PadLeft(5) + vbNewLine
Next
txtBox2.Text += "Total:".PadRight(12) + " = " + _
total.ToString().PadLeft(5)
The outer loop is essentially the same - split the input string on " " (space).
Reset the wordTotal counter to 0, and then loop through the current word (using For Each Character to go through the word one character at a time).
The next line uses TryGetValue on the dictionary, and if there is a value for the key, it adds the value to wordTotal, otherwise it adds 0.
The output will for "aaa bbb cc" will be:
aaa = 3
bbb = 15
cc = 14
Total: = 32
Here's a hint: What you are doing in this statement:
For Each cc As KeyValuePair(Of Char, Integer) In dicLetters
wordtotal += cc.Value
Next
For every key value pair in the dictionary add them up... so it adds up 1, 5 and 7 to give you 13.
Why not put a SELECT/CASE Statement checking the value of each letter against the dictionary and adding that to wordtotal

Get the number of occurrences out of textbox

Hi I'm trying to get the number of occurrences of a character out of a txtbox. Still haven't found the answer...
For example:
I give in a sentence... "Hello there!." and in a listbox there must be...
H - 2 times
e - 3 times
....
this is my code...
For i = 0 To txtSent.Text.Length - 1
If (Char.IsLetter(txtSent.Text(i))) Then
Dim str = Len(txtSent.Text) - Len(Replace(txtSen.Text, txtSen.Text(i), ""))
lstOutput.Items.Add(txtZin.Text(i) & " occurs " & str & " time(s)")
End If
Next´
But i need it to be "m - 5" instead of repeating all the characters of "m"
Can you help me?
Take a look at this article. Does exactly what you are after. http://msdn.microsoft.com/en-us/library/bb397940.aspx
This is a method in vb.net that should help you aswell.
Public Function GetNumSubstringOccurrences(ByVal text As String, ByVal search As String) As Integer
Dim num As Integer = 0
Dim pos As Integer = 0
If Not String.IsNullOrEmpty(text) AndAlso Not String.IsNullOrEmpty(search) Then
While text.IndexOf(search.ToLower(), pos) > -1
num += 1
pos = text.ToLower().IndexOf(search.ToLower(), pos) + search.Length + 1
End While
End If
Return num
End Function
To loop the alphabet, do the following
Dim s As String = "ssssddfffccckkkllkeeiol"
For Each c In "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray()
Console.WriteLine(GetNumSubstringOccurrences(s, c))
Next

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