Create a right triangle with loop in Visual Basic - vb.net

I tried to solve the Visual Basic assignment in dart and I was able to using this :
I don't know if that's the best way to do it though. In Visual Studio I don't know what commands or methods that can help me do this and this is the result there.
Public Class Form1
Dim input As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Text = "Nested Loops"
End Sub
Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label.Click
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles InputTextBox.TextChanged
input = Val(InputTextBox.Text)
End Sub
Private Sub ComputeButton_Click(sender As Object, e As EventArgs) Handles ComputeButton.Click
For outer As Integer = 1 To input
For inner As Integer = 1 To outer
ListBox.Items.Add("#")
Next
ListBox.Items.Add("")
Next
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox.SelectedIndexChanged
End Sub
End Class
I get this error when trying to treat it like dart
System.InvalidCastException: 'Conversion from string "#" to type 'Double' is not valid.'
I need help.

Consider:
For outer As Integer = 1 To input
Dim s as String
For inner As Integer = 1 To outer
s &= "#"
Next
ListBox.Items.Add(s)
Next
i.e. you want to have a string that grows by one # each time before you add it to the thing that will display it:
"#"
"##"
"###"
"####"
This uses simple string concatenation. In the future when you're programming for real (and e.g. wanting to run a process that creates millions of strings) you should consider using something designed for the job, such as a StringBuilder. This will be ok for some small handful of operations though
Though I'm rather puzzled why you use a listbox and not just a textbox..

Related

Having trouble with a lottery software

sorry to come in here like this looking for answers, but im actually really stumped. Im supposed to make an application using 2 forms, one to generate its own array and store user entered numbers into another array, and then display them on the second form and tell you how many of the numbers are in common
I cant get the numbers to show up on the second form at all, and I also cant really understand how to get how many numbers are matching, but I will when I can reference them properly in form 2. I got the arrays set up perfectly, but I cant even call the numbers from them to form 2. I need help calling the arrays from the first form to display on the next
Form 1 code
Public Class Form1
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Shared random As New Random()
Dim UserArray(4) As String
Dim LotteryArray(4) As String
Public Sub btnCheck_Click(sender As Object, e As EventArgs) Handles btnCheck.Click
If txtNumbers.Text <> "" Then
For i As Integer = 0 To 4
If UserArray(i) = "" Then
UserArray(i) = txtNumbers.Text
End If
Next
End If
For n As Integer = 0 To 9
Dim RandomNumber As Integer = CInt(Int(Rnd() * 5) + 1)
LotteryArray(4) = CStr(RandomNumber)
Next
End Sub
End Class
Form 2 Code
Public Class Form2
Public Sub btnOk_Click(sender As Object, e As EventArgs) Handles btnOk.Click
lblUser1.Text = Form1.UserArray(0)
lblUser2.Text = Form1.UserArray(1)
lblUser3.Text = Form1.UserArray(2)
lblUser4.Text = Form1.UserArray(3)
lblUser5.Text = Form1.UserArray(4)
lblRand1.Text = Form1.LotteryArray(0)
lblRand2.Text = Form1.LotteryArray(1)
lblRand3.Text = Form1.LotteryArray(2)
lblRand4.Text = Form1.LotteryArray(3)
lblRand5.Text = Form1.LotteryArray(4)
If Form1.LotteryArray(4) = Form1.UserArray(4) Then
MessageBox("CONGRATULATIONS!", "You Are The GRAND PRIZE WINNER!")
End If
Me.Close()
End Sub
End Class
I will address your first question. How to get your numbers into your second form.
You main problem is the Access modifier you used for your arrays. Dim is the equivalent of Private which means that the variable is only visible within the class. Friend is visible anywhere in the assembly. See https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/declared-elements/access-levels for more information. Don't change your event procedure Access to Public.
You have to let the user fill in another guess. The first loop in the Check button will only enter the same input 5 times. You need one entry on every click but you need to keep track of where you are in the array. Private NumberOfGuesses As Integer Note that this variable is Private. It doesn't need to be seen outside of the Form1 class.
We don't need to refill the LotteryArray on every click so I did it once in the Form.Load You were trying to use the Random class the way you use the old vb6 Random. The .net class is much easier.
To display the arrays on Form2, I used list boxes and loops. Saved a bit of typing.
If you still have a question about part 2 of your problem post another question. Show what you have tried.
Public Class Form1
Private random As New Random()
Friend UserArray(4) As Integer
Friend LotteryArray(9) As Integer
Private NumberOfGuesses As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For n As Integer = 0 To 9
Dim RandomNumber As Integer = random.Next(0, 10)
LotteryArray(n) = RandomNumber
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If NumberOfGuesses > 4 Then
MessageBox.Show("You have used up your guesses")
Form2.Show()
Me.Close()
End If
If TextBox1.Text <> "" Then
UserArray(NumberOfGuesses) = CInt(TextBox1.Text)
NumberOfGuesses += 1
TextBox1.Clear()
TextBox1.Focus()
End If
End Sub
End Class
Public Class Form2
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For Each number In Form1.UserArray
ListBox1.Items.Add(number)
Next
For Each number In Form1.LotteryArray
ListBox2.Items.Add(number)
Next
End Sub
End Class

Visual Basic Beginner ..SubStrings

I'm new to programming and I'm trying to figure out this simple question! The language is Visual Basic! The Question is below:
"Users of a computer program often like to enter numbers with commas inserted in the middle, such as "1,234,000,688". Most computer languages consider this format to be non numeric. Write a program that inputs a number containing no more than three commas, and produces a string containing the same number without the commas"
When I enter this number: 1,234,000,688 and hit Display in Visual Basic I get this error message --> Argument is out of range Exception was unhanded
I'm not exactly sure why this is happening because I'm within my strUserInput length.
My Code:
Public Class Form1
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
'Variable declarations
Dim strUserInput = txtUserInput.Text
Dim strOutputNumber1 As String
Dim strOutputNumber2 As String
Dim strOutputNumber3 As String
Dim strOutputNumber4 As String
' 1,234,000,688
strOutputNumber1 = strUserInput.Substring(0, 1)
strOutputNumber2 = strUserInput.Substring(2, 4)
strOutputNumber3 = strUserInput.Substring(5, 8)
strOutputNumber4 = strUserInput.Substring(9, 12)
lblDisplayNumber.Text = strOutputNumber1 & strOutputNumber2 & strOutputNumber3 & strOutputNumber4
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
lblDisplayNumber.Text = String.Empty
txtUserInput.Text = String.Empty
End Sub
End Class
You're getting that exception because of the way you're using substring, the last one there starts at index 9 and extends 12 characters...that would be a 22 character number, and the text you have as input is probably much shorter. You don't need to make things overly complicated for yourself using substrings, all of the above code could be greatly condensed and cleaned up by simply using String.Replace like this:
Public Class Form1
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
lblDisplayNumber.Text = txtUserInput.Text.Replace(",", "")
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
lblDisplayNumber.Text = String.Empty
txtUserInput.Text = String.Empty
End Sub
End Class

Copying multiple sources to single destination

I am new to VB.net and am trying to create a backup utility to copy a set of local folders to a single backup destination (on usb for example) with a progress bar. After googling for the last few hours I can only find examples of single folder to single destination.
Can anyone point me in the direction of an example?
UPDATE:
Based of #Werdna example, I have created a simple FOR EACH NEXT loop. However the next issue is that only the files within the source directories are being copied to the target directory, rather than the folders and all their contents. Can anyone see where I am going wrong?
Public Class Form1
Private Sub Start_Click(sender As Object, e As EventArgs) Handles Start.Click
Dim destination = "E:\Backup Folder"
Dim sources As New List(Of String)
sources.Add("D:\Profiles\Users\Desktop")
sources.Add("D:\Profiles\Users\Mail")
sources.Add("D:\Profiles\Users\Downloads")
For Each source As String In sources
My.Computer.FileSystem.CopyDirectory(source, destination)
Next
MessageBox.Show("Copy Completed")
End Sub
End Class
Also, what is the best method to use the FOR EACH NEXT loop to count the number of files to be copied? I would like to output the amount to a label as well as use it for a progressbar as the utility evolves.
here is something that i have quickly written up for you to give you some idea on how i went about completing your task. You will need to add 2 listboxes to your application, a folder open dialog and a few buttons, this might not be what you are looking for, unfortunately you cant select multiable folders with the other dialogs, however nevertheless, take a look below, the code isn't completely as there is always something to do, however this should lead you in the right direction hopefully!
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For Each item In IO.Directory.GetDirectories("C:\")
ListBox1.Items.Add(item)
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For Each item In ListBox1.SelectedItems
ListBox2.Items.Add(item & "\")
Next
ListBox1.SelectedItem = Nothing
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
ListBox2.Items.Remove(ListBox2.SelectedItem)
ListBox2.SelectedItem = Nothing
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
For Each item In IO.Directory.GetDirectories(ListBox1.SelectedItem)
ListBox1.Items.Clear()
ListBox1.Items.Add(item)
Next
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
If FolderBrowserDialog1.ShowDialog = DialogResult.OK Then
My.Computer.FileSystem.CreateDirectory(FolderBrowserDialog1.SelectedPath)
For Each item In ListBox2.Items
My.Computer.FileSystem.CopyDirectory(item, FolderBrowserDialog1.SelectedPath)
Next
MessageBox.Show("Copy Completed.")
End If
End Sub
End Class
I wrote this in about 10 minutes, so i didnt get a change to do a progessbar, however if this is what you are looking for, then i am happy to help you add one to your program. Happy Coding!
UPDATE - BASED OFF YOUR NEW QUESTION
Public Class Form1
Dim NumberofFILEs As Integer = 0
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Dim Location1 = "C:\Backup Folder\TESTING\FOLDER"
Dim source As String = "C:\TESTING\FOLDER"
Dim source1 As String = "C:\TESTING1\FOLDER"
Dim Location2 = "C:\Backup Folder\TESTING1\FOLDER"
IO.Directory.CreateDirectory("C:\Backup Folder\TESTING\FOLDER")
IO.Directory.CreateDirectory("C:\Backup Folder\TESTING1\FOLDER")
For Each item In source
My.Computer.FileSystem.CopyDirectory(source, Location1, True)
Next
For Each item In source1
My.Computer.FileSystem.CopyDirectory(source1, Location2, True)
Next
MessageBox.Show("Completed")
For Each file In source1.Count & source.Count
NumberofFILEs += 1
Next
Label1.Text = NumberofFILEs
End Sub
End Class
Edit the locations and destinations to what you need. Also the True at the end of the copydirectory means that it will overwrite any files with the same name, eg it will update them pretty much
You can copy each folder to the destination, one at a time. Loop through the source folders and copy each one to the target folder.

The form just freeze looping throught lines

I'm just stuck into something in which I can't solve it in any way. My UI freeze even with BackgroundWorker.
Regarding to my old solved problem: VB.NET - It keep replacing itself
'I have in a text file lines of this format:
word1|word2|word3
anotherword1|anotherword2
I'm trying to split each word one by one per every line of that file and once program detect if the richtextbox has one of these words will replace that word with the unsplitted line. Example: From word1 to word1|word2|word3'
Everything works great, but only if I'm using a file with a small set of lines to split. But I need to split a big one at once.
Here is what I have so far: http://pastebin.com/raw/k0MtPHbZ
As I said, everything works if I reduce the lines of the en.txt file and I'm kinda confused why. I would really appreciate if someone would tell me how to fix this problem.
UPDATE:
As you guys said look what I did:
Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim list As New List(Of String)()
Using reader As New StreamReader(Application.StartupPath & "\en.txt")
Dim line As String = Nothing
Dim input = RichTextBox1.Text
While (InlineAssignHelper(line, reader.ReadLine())) IsNot Nothing
Dim pat = String.Format("\b({0})\b", line)
input = Regex.Replace(input, pat, line)
End While
RichTextBox2.Text = input
End Using
End Sub
But it still does the same. Work fine with small amount of lines. Freeze with my 500kb text file.
I believe your background worker is still going to block on your UI thread because you're referencing UI controls in the DoWork portion. You would be better off pulling in the data on the UI thread, assigning it to a variable, and then processing that all in memory in the DoWork instead of attempting to manipulate UI from a background thread, this is going to give you grief consistently.
So in your button1.Click handler, get the input from the textbox and assign it to an instance variable. Reference that instance variable inside your DoWork for the input.
Example:
Public Class Form1
Private _textInput As String = String.Empty
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
_textInput = RichTextBOx1.Text
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, value As T) As T
target = value
Return value
End Function
Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
For i = 0 To 100
Threading.Thread.Sleep(200)
Dim list As New List(Of String)()
Using reader As New StreamReader(Application.StartupPath & "\en.txt")
Dim line As String = Nothing
While (InlineAssignHelper(line, reader.ReadLine())) IsNot Nothing
Dim pat = String.Format("\b({0})\b", line)
_textInput = Regex.Replace(_textInput , pat, line)
End While
End Using
BackgroundWorker1.ReportProgress(i)
Next
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
ProgressBar1.Value = e.ProgressPercentage
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
MsgBox("done")
RichTextBox1.Text = _textInput
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
End Class
Your Pastebin link includes the following code:
For i = 0 To 100
Threading.Thread.Sleep(200)
[...]
Next
At a glance, why are you putting the thread to sleep for a fifth of a second on every iteration of the for-loop?
Remove this line for starters.

Save changes made to file names in folder. All 762 of them

I downloaded a pack of roms for a SNES emulator and when I went to transfer them over I received an error on the illegal file names. So I started coding a simple app that will remove the problem char from the roms title. I got that part figured out however I cannot figure out how to save the edited file names. Keep in mind there are 762 roms in the folder so manually doing this is not an option. Thanks in advance for any guidance.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListBox1.Items.AddRange(IO.Directory.GetFiles("c:\ROMS"))
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim Index As Integer = ListBox1.SelectedIndex
Dim Results = (From T In ListBox1.Items
Select System.Text.RegularExpressions.Regex.Replace(CStr(T),
"[""]", String.Empty).Replace("[!]", "")
).ToArray
ListBox1.Items.Clear()
ListBox1.Items.AddRange(Results)
If Index <> -1 Then
ListBox1.SelectedIndex = Index
End If
End Sub
End Class
I am using button1 to open the folder into a listbox.
Button 2 removes the unwanted [!] from the title
Button 3 would be where the save feature is.
####### EDIT #####
I figured out what the real problem was for my particular case.
I was transferring the folder of roms over to my Xbox and apparently the is a character limit not so much a restriction on chars used. Dont know the actual allowed amount of chars to be used but for anyone who may be trying to do what I did just use my code to remove unnecessary chars in the title.
Add another Listbox to your form called Listbox2 then use this code below. Also notice in Button2 the use of GetDirectoryName and GetFileName so that you don't replace any chars in the folder name...only the filename
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListBox1.Items.AddRange(IO.Directory.GetFiles("c:\ROMS"))
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim Index As Integer = ListBox1.SelectedIndex
Dim Results = (From T In ListBox1.Items
Select IO.Path.GetDirectoryName(CStr(T)) & "\" & System.Text.RegularExpressions.Regex.Replace(IO.Path.GetFileName(CStr(T)),
"[""]", String.Empty).Replace("[!]", "")
).ToArray
ListBox2.Items.Clear()
ListBox2.Items.AddRange(Results)
If Index <> -1 Then
ListBox1.SelectedIndex = Index
ListBox2.SelectedIndex = Index
End If
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
For x As Integer = 0 To Me.ListBox1.Items.Count - 1
IO.File.Move(Me.ListBox1.Items(x), Me.ListBox2.Items(x))
Next
MsgBox("Done!")
End Sub
End Class