Displaying the sum of a range of numbers? - vb.net

I have to create a program that calculates the sum of a range of numbers entered by the user and displays in a label an expression with the numbers in range. So if I entered "10" as a starting number and "20" as an ending number, there would be a label that displays "10+11+12+13+14+15+16+17+18+19+20".
This is what I have so far. I'm not sure how to get the range of numbers and display it in a label. I'm also really new to Visual Basic (I'm taking it as a course in high school) so please dumb down your answer as much as possible :) Any help is appreciated! Thanks.
Dim intStartingNumber As Integer = Val(Me.txtStartNumber.Text)
Dim intEndingNumber As Integer = Val(Me.txtEndNumber.Text)
Dim intSum As Integer = 0
Me.lblNumbers.Text = intStartingNumber & "+" & intEndingNumber
For intStartingNumber = Val(Me.txtStartNumber.Text) To intEndingNumber Step 1
intSum = intSum + intStartingNumber
Next
Me.lblNumbersSum.Text = intSum

If you just want the total:
Dim StartNumber As Integer = Integer.Parse(txtStartNumber.Text)
Dim EndNumber As Integer = Integer.Parse(txtEndNumber.Text)
lblNumbersSum.Text = Enumerable.Range(StartNumber, EndNumber - StartNumber ).Sum()
If you really want the full text expressions:
Dim StartNumber As Integer = Integer.Parse(txtStartNumber.Text)
Dim EndNumber As Integer = Integer.Parse(txtEndNumber.Text)
Dim delimiter As String = ""
Dim expression As New StringBuilder()
For Each number As String IN Enumerable.Range(StartNumber, EndNumber - StartNumber )
expression.Append(delimiter).Append(number)
delimiter = "+"
Next number
lblNumbersSum.Text = expression.ToString()

This should work, albeit I haven't been able to test:
Dim intStartingNumber As Integer = Val(Me.txtStartNumber.Text)
Dim intEndingNumber As Integer = Val(Me.txtEndNumber.Text)
Dim intSum As Integer = 0
Dim intIndex As Integer
Dim strExpr As String
strExpr = Me.txtStartNumber.Text
'Setting up a new variable called intIndex so that intStartingNumber can stay static
For intIndex = Val(Me.txtStartNumber.Text) To intEndingNumber Step 1
intSum = intSum + intIndex
if intIndex > intStartingNumber Then
strExpr = strExpr & "+" & intIndex
End If
Next
Me.lblNumbersSum.Text = intSum
Me.lblNumbers.Text = strExpr
The idea is that you create a new variable called strExpr to hold the expression and then concatenate using & within the For loop. That way, as you add on the values arithmetically, you're also adding to the string that shows the calculation being done. I'm hoping that's what you were after.
If you get any errors, please comment below and I'll amend the script and explain.

As you are doing this to learn the basics of Basic (hah hah, never heard that one before), I will keep it simple:
' convert the input text into numbers
Dim startNumber As Integer = Integer.Parse(txtStartNumber.Text)
Dim endNumber As Integer = Integer.Parse(txtEndNumber.Text)
'TODO: optional - check that endNumber > startNumber
' we are going to put the sum and the text of the summation into
' variables; we might as well start them off with the first values
Dim sum As Integer = startNumber
Dim sumText As String = startNumber.ToString()
' now we just need to use a loop that goes from the second value to the end
For i As Integer = startNumber + 1 To endNumber
' we need to use the value i twice, once as a number...
sum = sum + i
' ... and once as a String
sumText = sumText & "+" & i.ToString()
Next
' show the results to the user
lblNumbersSum.Text = sum.ToString()
lblNumbers.Text = sumText
The default Step value for a For..Next loop is 1, so we don't need to specify that.
Instead of writing sum = sum + i, we could write sum += i, and similarly for sumText = sumText & "+" & i.ToString() we could write sumText &= "+" & i.ToString(). They are just ways of saving a bit of typing.
As Jens mentioned, it is usually better to use something called a StringBuilder to build a string in a loop, but I expect you will learn about that later. If you want to learn about it now, you could look at the Remarks section of the StringBuilder documentation.

Related

How To Replace or Write the Sentence Backwards

I would like to have a block of code or a function in vb.net which can write a sentence backwards.
For example : i love visual basic
Result : basic visual love i
This is what I have so far:
Dim name As String
Dim namereversed As String
name = RichTextBox1.Text
namereversed = ""
Dim i As Integer
For i = Len(name) To 1 Step -1
namereversed = namereversed & Replace(name, i, 1)
Next
RichTextBox2.Text = namereversed
The code works but it does not give me the value of what i want. it makes the whole words reversed.
Dim name As String = "i love visual basic"
Dim reversedName As String = ""
Dim tempName As String = ""
For i As Integer = 0 To name.Length - 1
If Not name.Substring(i, 1).Trim.Equals("") Then
tempName += name.Substring(i, 1)
Else
reversedName = tempName + " " + reversedName
tempName = ""
End If
Next
start from index 0 and deduct 1 from length because length count starts with one but index count starts with zero. if you put To name.Length it will return IndexOutOfBounds. Loop it from 0 To Length-1 because you need the word as is and not spelled backwards... what are placed in reverse are the words so add a temporary String variable that stores every word and add it before the saved sentence/words.
or use this
Dim strName As String() = name.Split(" ")
Array.Reverse(strName)
reversedName = String.Join(" ", strName)
This is my contribution, well as you can see its not hard to do, its really simple. There are a lot of other ways which are more short.
Console.Title = "Text Reverser"
Console.ForegroundColor = ConsoleColor.Green
'Text which will be Reversed
Dim Text As String
Console.Write("Write your text: ")
Text = Console.ReadLine
Console.Clear()
Dim RevText As String = "" '← The Text that will be reversed
Dim Index As Int32 = Text.Length '← Index used to write backwards
'Fill RevText with a char
Do Until RevText.Length = Text.Length
RevText = RevText.Insert(0, "§")
Loop
Console.WriteLine(RevText)
'Replace "Spaces" with Character, using 'Index' to know where go the chars
For Each Caracter As Char In Text
Index -= 1 'Rest 1 from the Index
RevText = RevText.Insert(Index, Caracter) '← Put next char in the reversed text
'↓ Finished reversing the text
If Index = 0 Then
RevText = RevText.Replace("§", "") 'Replace char counter to nothing
Console.WriteLine("Your text reversed: " & RevText) '← When Index its 0 then write the RevText
End If
Next
'Pause
Console.ReadKey()
I've done this project in a console, but you know, you can use this code in a normal Windows Form.
This is my first Answer in Stackoverflow :)

In string search for number to determine next in sequence?

I have a list of build numbers (e.g. R1079-AAA-001, ...-002 etc.) in which the value of "R1079" changes depending on the machine being used. What I want to do is search through the list to determine the last used build number (the last 3 digits) in relation to the specific machine I intend to use. I then need to add one and create a new log for the new build i.e. the last R1079 build was 056, therefore the new one is 057.
Currently the THEORY I have is an in string search for the machine number followed by a number search and store in the string and converted to integer. This is then added into a dynamic array and the maximum found when the loop is complete. One is added to this integer and the new name placed into a cell.
However, the code I have doesn't work so I assume I am missing things/got it all wrong.
Code below:
Sub test()
Dim x As String
Dim n As Integer
Dim i As Integer
Dim Machine_EBM As String
Dim retval As String
Dim retvalint As Integer
Dim LastBuild As Integer
Dim NextBuild As Integer
Dim myarr() As Integer
Machine = "R1079"
x = Cells("A1").Value 'get the first string in the list
n = 1
Do Until x = ""
If InStr(x, Machine) > 0 Then 'search for machine in string
For i = 6 To Len(Str) 'search for numbers at end of string
If Mid(x, i, 1) >= "0" And Mid(x, i, 1) <= "9" Then
retval = retval + Mid(s, i, 1) 'store numbers
End If
Next i
retvalint = CInt(retval) ' convert to integer
ReDim Preserve myarr(n)
myarr(n) = retvalint ' store integer value in array
n = n + 1
End If
Loop
LastBuild = Worksheet.Function.Max(myarr(n)) ' determine maximum array value
NewBuild = LastBuild + 1 'add one to the value
Range("C1").Select
ActiveCell = Machine = "-AAA-" + NewBuild 'input new build number
End Sub
I am fairly new to VBA and self taught so I realise there may be a lot of errors here that I am missing. Any help is appreciated!
Thanks,
Charlie
Here is a small piece of code for getting new build no for inputted build no.
I already tested the code. It give me right answer. So, you can use this code.
Public Sub getBuildNo()
Dim machineCode, lastBuildCode, newBuildCode As String
Dim buildNo As Integer
'Set machine code
machineCode = "R1079"
'Set last build code
lastBuildCode = Range("A1")
'Get last build no
buildNo = Right(lastBuildCode, 3)
'Increase 1
buildNo = buildNo + 1
'Get new build No
newBuildCode = machineCode & "-AAA-"
'adding prefix 0s for getting like (001, 002, 025, etc.)
If buildNo < 10 Then
newBuildCode = newBuildCode & "00" & buildNo
ElseIf buildNo < 100 Then
newBuildCode = newBuildCode & "0" & buildNo
Else
newBuildCode = newBuildCode & buildNo
End If
'show new code
Range("C1") = newBuildCode
End Sub

manipulate StringBuilder in vb.net

I have a Note as stringBuilder with word and date: reval 41/50/50
I want to manipulate it, so I will have: reval 05/05/14.
(The date is only when I have the word reval before)
My function is:
Sub correctDateShowing(ByRef Note As StringBuilder)
Dim index, i, j As Integer
For index = 0 To Note.Length - 2
If (Note(index).ToString = "r" And Note(index + 1).ToString = "e") Then
For i = 6 To Note.Length - 1 'start from 6,because I want only the date to be reversed
'Here I am Stuck!!
Next
End If
Next
End Sub
I try to do some replacing with a tmp variable but it didn't work.
I will be glad to get some help.
Thanks All!!!
Sub CorrectDateShowing(ByRef Note As StringBuilder)
Dim str As String = Note.ToString()
Dim arr As String() = str.Split(" "c)
arr(1) = StrReverse(arr(1))
Note = New StringBuilder(arr(0) & " " & arr(1))
End Sub
Split the text into two parts, reverse the second part (the date) and then reconnect them.
Try this:
Dim tempCharArray As char[]
Dim dateStartIndex, dateLength As int
'' Here you need to calculate the date start index and date length (i guess the date length is always 8)
Note.CopyTo(dateStartIndex, tempCharArray, 0, dateLength)
Note.Replace(new String(tempCharArray), new String(Array.Reverse(tempCharArray)), dateStartIndex, dateLength)

generate random string

well i know that there are a lot of these threads but im new to vb.net yet i cant edit the sources given to make what i really want
so i want a function that will generate random strings which will contain from 15-32 characters each and each of them will have the following chars ( not all at the same string but some of them ) :
A-Z
a-z
0-9
here is my code so far
Functon RandomString()
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim r As New Random
Dim sb As New StringBuilder
For i As Integer = 1 To 8
Dim idx As Integer = r.Next(0, 35)
sb.Append(s.Substring(idx, 1))
Next
return sb.ToString()
End Function
Change the string to include the a-z characters:
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Change the loop to create a random number of characters:
Dim cnt As Integer = r.Next(15, 33)
For i As Integer = 1 To cnt
Note that the upper boundary in the Next method is exclusive, so Next(15, 33) gives you a value that can range from 15 to 32.
Use the length of the string to pick a character from it:
Dim idx As Integer = r.Next(0, s.Length)
As you are going to create random strings, and not a single random string, you should not create the random number generator inside the function. If you call the function twice too close in time, you would end up with the same random string, as the random generator is seeded using the system clock. So, you should send the random generator in to the function:
Function RandomString(r As Random)
So, all in all:
Function RandomString(r As Random)
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Dim sb As New StringBuilder
Dim cnt As Integer = r.Next(15, 33)
For i As Integer = 1 To cnt
Dim idx As Integer = r.Next(0, s.Length)
sb.Append(s.Substring(idx, 1))
Next
return sb.ToString()
End Function
Usage example:
Dim r As New Random
Dim strings As New List<string>()
For i As Integer = 1 To 10
strings.Add(RandomString(r))
Next
Try something like this:-
stringToReturn&= Guid.NewGuid.ToString().replace("-","")
You can also check this:-
Sub Main()
Dim KeyGen As RandomKeyGenerator
Dim NumKeys As Integer
Dim i_Keys As Integer
Dim RandomKey As String
''' MODIFY THIS TO GET MORE KEYS - LAITH - 27/07/2005 22:48:30 -
NumKeys = 20
KeyGen = New RandomKeyGenerator
KeyGen.KeyLetters = "abcdefghijklmnopqrstuvwxyz"
KeyGen.KeyNumbers = "0123456789"
KeyGen.KeyChars = 12
For i_Keys = 1 To NumKeys
RandomKey = KeyGen.Generate()
Console.WriteLine(RandomKey)
Next
Console.WriteLine("Press any key to exit...")
Console.Read()
End Sub
Using your function as a guide, I modified it to:
Randomize the length (between minChar & maxCharacters)
Randomize the string produced each time (by using the static Random)
Code:
Function RandomString(minCharacters As Integer, maxCharacters As Integer)
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Static r As New Random
Dim chactersInString As Integer = r.Next(minCharacters, maxCharacters)
Dim sb As New StringBuilder
For i As Integer = 1 To chactersInString
Dim idx As Integer = r.Next(0, s.Length)
sb.Append(s.Substring(idx, 1))
Next
Return sb.ToString()
End Function
Try this out:
Private Function RandomString(ByRef Length As String) As String
Dim str As String = Nothing
Dim rnd As New Random
For i As Integer = 0 To Length
Dim chrInt As Integer = 0
Do
chrInt = rnd.Next(30, 122)
If (chrInt >= 48 And chrInt <= 57) Or (chrInt >= 65 And chrInt <= 90) Or (chrInt >= 97 And chrInt <= 122) Then
Exit Do
End If
Loop
str &= Chr(chrInt)
Next
Return str
End Function
You need to change the line For i As Integer = 1 To 8 to For i As Integer = 1 To ? where ? is the number of characters long the string should be. This changes the number of times it repeats the code below so more characters are appended to the string.
Dim idx As Integer = r.Next(0, 35)
sb.Append(s.Substring(idx, 1))
My $.02
Dim prng As New Random
Const minCH As Integer = 15 'minimum chars in random string
Const maxCH As Integer = 35 'maximum chars in random string
'valid chars in random string
Const randCH As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Private Function RandomString() As String
Dim sb As New System.Text.StringBuilder
For i As Integer = 1 To prng.Next(minCH, maxCH + 1)
sb.Append(randCH.Substring(prng.Next(0, randCH.Length), 1))
Next
Return sb.ToString()
End Function
please note that the
r.Next(0, 35)
tend to hang and show the same result Not sure whay; better to use
CInt(Math.Ceiling(Rnd() * N)) + 1
see it here Random integer in VB.NET
I beefed up Nathan Koop's function for my own needs, and thought I'd share.
I added:
Ability to add Prepended and Appended text to the random string
Ability to choose the casing of the allowed characters (letters)
Ability to choose to include/exclude numbers to the allowed characters
NOTE: If strictly looking for an exact length string while also adding pre/appended strings you'll need to deal with that; I left out any logic to handle that.
Example Usages:
' Straight call for a random string of 20 characters
' All Caps + Numbers
String_Random(20, 20, String.Empty, String.Empty, 1, True)
' Call for a 30 char string with prepended string
' Lowercase, no numbers
String_Random(30, 30, "Hey_Now_", String.Empty, 2, False)
' Call for a 15 char string with appended string
' Case insensitive + Numbers
String_Random(15, 15, String.Empty, "_howdy", 3, True)
.
Public Function String_Random(
intMinLength As Integer,
intMaxLength As Integer,
strPrepend As String,
strAppend As String,
intCase As Integer,
bIncludeDigits As Boolean) As String
' Allowed characters variable
Dim s As String = String.Empty
' Set the variable to user's choice of allowed characters
Select Case intCase
Case 1
' Uppercase
s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Case 2
' Lowercase
s = "abcdefghijklmnopqrstuvwxyz"
Case Else
' Case Insensitive + Numbers
s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
End Select
' Add numbers to the allowed characters if user chose so
If bIncludeDigits = True Then s &= "0123456789"
Static r As New Random
Dim chactersInString As Integer = r.Next(intMinLength, intMaxLength)
Dim sb As New StringBuilder
' Add the prepend string if one was passed
If String.IsNullOrEmpty(strPrepend) = False Then sb.Append(strPrepend)
For i As Integer = 1 To chactersInString
Dim idx As Integer = r.Next(0, s.Length)
sb.Append(s.Substring(idx, 1))
Next
' Add the append string if one was passed
If String.IsNullOrEmpty(strAppend) = False Then sb.Append(strAppend)
Return sb.ToString()
End Function

How to get an array to display all its values at once

Here is some sample code:
Dim arrValue(3) as Integer
arrValue(0) = 5
arrValue(1) = 4
arrValue(2) = 7
arrValue(3) = 1
How can I display those four values next to each other.
More specifically, given those values how can I make txtValue.Text = 5471
Edit:
The idea I had would be to use some sort of function to append each one to the end using a loop like this:
Dim finalValue
For i As Integer = 3 To 0 Step -1
arrValue(i).appendTo.finalValue
Next
Obviously that code wouldn't work though the premise is sound I don't know the syntax for appending things and I'm sure I wouldn't be able to append an Integer anyway, I would need to convert each individual value to a string first.
Another method is to use String.Join:
Sub Main
Dim arrValue(3) as Integer
arrValue(0) = 5
arrValue(1) = 4
arrValue(2) = 7
arrValue(3) = 1
Dim result As String = String.Join("", arrValue)
Console.WriteLine(result)
End Sub
If I understand your question correctly, you can use StringBuilder to append the values together.
Dim finalValue as StringBuilder
finalValue = new StringBuilder()
For i As Integer = 3 To 0 Step -1
finalValue.Append(arrValue(i))
Next
Then just return the finalValue.ToString()
Convert the integers to strings, and concatenate them:
Dim result as String = ""
For Each value as Integer in arrValue
result += value.ToString()
Next
Note: using += to concatenate strings performs badly if you have many strings. Then you should use a StringBuilder instead:
Dim builder as New StringBuilder()
For Each value as Integer in arrValue
builder.Append(value)
Next
Dim result as String = builder.ToString()
for i = lbound(arrValue) to ubound(arrValue)
ss=ss & arrValue(i)
next i
end for
debug.print ss
Dim value as string = ""
For A As Integer = 1 To Begin.nOfMarks
value += "Mark " & A & ": " & (Begin.Marks(A)) & vbCrLf
Next A