I need help outputting squares of numbers separated by commas - vb.net

Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
TextBox2.Text = TextBox1.Text ^ 2
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
TextBox1.Text = Nothing
TextBox2.Text = Nothing
End Sub
End Class
The code above outputs squares of any single values input in textbox1 but i need some help in inputting a couple of values separated by commas and then output the squares of those individual values eg 3,4 the output 9,16

I'm not going to do it all for you, because this looks like homework, but here are some pointers:
TextBox2.Text = TextBox1.Text ^ 2
1) Turn on Option Strict, by placing Option Strict On at the top of your code file or by putting it in the project properties Compile tab. This will help you be more rigorous with your coding. Here you're taking a string (TextBox1.Text) and having VB auto convert it to a number (which might fail), squaring it, and then auto converting it back to a string to store in TextBox2.Text. This is bad news all round; always be crystal clear in your own mind and explicit in your coding about the difference between various data types.A string containing numbers is not the same thing as a number!
2) Rename your textboxes after you drop them on a form. Nothing is more frustrating than to read a block of code where the variable names are irrelevant garbage. You will find this when you come back to some complex code in 6 months and think "what the..."; renaming a textbox so it is called resultTextBox or inputTextBox takes seconds and makes your code instantly more comprehensible to both you and anyone you call in to help out with it
separated by commas
The following line of code will split a string into an array of strings, on comma:
Dim csv = "3,6"
Dim arr = csv.Split(","c)
Console.WriteLine(arr(0)) 'prints 3
Console.WriteLine(arr(1)) 'prints 6
The following line of code will convert a string to an integer:
Dim s = "3"
Dim i = Convert.ToInt32(s)
Maths operations can now be performed on it
i = i * i 'square it
The following line of code will turn an integer into a string:
Dim i as Integer = 3
Dim s as String = i.ToString() 's is now "3"
The following line of code will loop through an array, appending the values in the array to a string variable, and adding commas. Finally it trims off the excess trailing comma
Dim s as New String
For Each x as String in arr
s = s & x & ","
Next x
s = s.TrimEnd(","c)
Here is another way too, using the String.Join helper method:
Dim s as String = String.Join(","c, arr)

Related

How to assign values from a file to variable

I have a text file and I wish to make code that puts the numbers into an array.
The program is required to read the data for each member from the text file. The program then uses this data to find then display the biggest value. The names of every member who has a value more than 70% of the largest is to be written on an empty text file so that the file can be printed out later.
Nikolai,Bryant,145.6
Susan,Brown,34.2
Teressa,Jones,398.5
Martin,Daly,256.9
Ross,Durrant,409.0
Greg,Watson,99.2
Wendy,Russell,87.4
Pamela,Adkins,73.6
Ian,Hunter,385.7
James,Kerr,505.2
Lesley,Wallace,68.4
Kim,Pettigrew,256.4
Steven,Johnstone,23.4
Ali,Hussain,12.1
Hasan,Abbas,302.0
Jacek,Nowak,199.9
Mirka,Kowalski,176.8
Rudo,Hyper,120.2
Tisa,Sullivan,484.2
Albert,Nvodo,385.8
So far all I have is this:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim FILE_NAME As String = "H:\S5\Computing\Programming\members.txt"
Dim objReader As New System.IO.StreamReader(FILE_NAME)
End Sub
End Class
You will need to add Imports System.IO at the top of you code file. This has a File class which contains the .ReadAllLines method. This method will return an array of all the lines in the text file.
'String.Split' will return an array of of the fields in the line which were delimited (separated) by a comma. The small c after "," tells the compiler that this is Char which what the .Split method expects.
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim FILE_NAME As String = "H:\S5\Computing\Programming\members.txt"
Dim lines = File.ReadAllLines(FILE_NAME)
'Declare an array to hold your numbers VB arrays are declared arr(UBound)
'UBound is upper bound referring to highest index
'The highest index would be 1 less the lenght because indexes start at 0
Dim numbers(lines.Length - 1) As Single
Dim index As Integer 'Will be the index for the numbers array
'From the lines array we can loop through each line
For Each s As String In lines
Dim fields = s.Split(","c)
'Your fields array will have 3 elements, a first name at position (index) 0, last name at 1 and number at 2
'You only want the number - but it is not a number yet, it is still a string
'So we do a CSng to change it to a Single
numbers(index) = CSng(fields(2))
index += 1 'shortcut way to write index = index + 1
Next
For Each n As Single In numbers
Debug.Print(n.ToString)
Next
End Sub
The .TexFieldParser suggested by #jmcilhinney in comments has some extra features which would come in handy but this should get you started.

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
Here is what I have so far:
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
For Each line As String In File.ReadLines("C:\text.txt")
Dim input As String = line
Dim result As String() = line.Split(New String() {"|"}, StringSplitOptions.None)
For Each s As String In result
Try
Dim linex As String = line
RichTextBox1.Text = RichTextBox1.Text.Replace(s, " " & linex)
Catch exxx As Exception
End Try
Next
Next
End Sub
It works great, but after the replacement, the replaced text still have the detected word and it keep replacing itself with word1|word2|word3 forever. And I want do do the process just once.
Like this: Click to see
Due to the format the words are stored in, it will be much easier to achieve what you want using Regular Expressions:
Dim lines = File.ReadLines("C:\text.txt")
For Each line As String In lines
Dim pat = String.Format("\b({0})\b", line)
RichTextBox1.Text = Regex.Replace(RichTextBox1.Text, pat, line)
Next
This should do pretty much what you want.
Check it here.

loop - reading text after a certain string up until a certain string

start=AKS-RHzlSXSftLGYdBNk.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1&
For every instance of the word 'start' I need to be able to get the text after the first full stop, right up until the & symbol. E.g. 'eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1'.
There will be more than one instance of this. They will need to be appended to a listbox.
What is the simplest/quickest way to do this? (Using possibly streamreader - text file)
The simplest and quickest way will be to read each line, and check if it .StartsWith("start="). If so, then get the .IndexOf(".") and the .IndexOf("&", <whereever the first indexOf was>). Get the .SubString which encompasses those two values. I'm sure you can write the code yourself from that ;)
I tested this function with a button click, output text each line on a textbox. I am sure you can adapt this to your code.
Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
txtResults.Text = ""
Dim ParseString As String
ParseString = "start=123341.23124&kjdshfkjsdaksdstart=1231.2321312&kadhskjashdkjastart=1231.23126789898&skjdfhkjsd"
Dim Delimiters() As String = New String() {"start="}
Dim Words() As String
Words = ParseString.Split(Delimiters, CompareMethod.Text)
For Each Part In Words
Dim Middle As String
Middle = Part.Split(".").Skip(1).Take(1).FirstOrDefault()
Dim Good As String
Good = Middle.Split("&").FirstOrDefault()
txtResults.Text += Good + vbNewLine
Next
End Sub
Output was
23124
2321312
23126789898
Added 31104 lines to a string and ran, took about 11 seconds to run on my laptop. Might be too slow for your app?

How can I get specific items from text file? Visual Basic 2010

I am trying to figure out how to get a message box to show only specific words from a text file, which contains all of the words within the dictionary. I have tried various different ways, but cannot get it to work, but I do think I am on the right track so just need some pointers.
Basically, there is a scrambled up string, which is different every time, and is contained within a label. I want the program to only show words which contains the letters inside the scrambled string, but not sure how to achieve this?
Here is the code that I have so far:
Private Sub btnAnswers_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAnswers.Click
Dim hash As List(Of String) = New List(Of String)(System.IO.File.ReadAllLines("C:\Users\Katie\Documents\Project\dictionary.txt"))
Dim Letters As String
Dim OneCharacter As String
Dim Found As Boolean
Dim item As String
Dim AllCharacters As String
Found = False
Letters = lblLetters.Text
For i = 0 To Letters.Length - 1
OneCharacter = Letters.Substring(i, 1)
For Each item In hash
If item.Contains(OneCharacter) Then
Found = True
AllCharacters = OneCharacter
Else
Found = False
End If
MsgBox(item)
Next
Next i
End Sub
The message box does show up words, from the dictionary, but words can contain letters that are not present in the label string, so my code is wrong. Can anyone help? Apologies, but I am new to programming.
With a simple modification to the previous answer you can restrict the output to only words that contain only the scrambled letters:
Private Sub btnAnswers_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim hash As List(Of String) = New List(Of String)(System.IO.File.ReadAllLines("C:\Users\Katie\Documents\Project\dictionary.txt"))
Dim Letters As String = lblLetters.Text
For Each item As String In hash
Dim word As String = item.ToLower()
For i = 0 To Letters.Length - 1
Dim OneCharacter As Char = Char.ToLower(Letters(i))
While word.Contains(OneCharacter)
word = word.Remove(word.IndexOf(OneCharacter), 1)
End While
Next
If (word.Length = 0) Then
'The given dictionary entry includes all the letters in the label. No more iterations will be performed
MsgBox(item)
Exit For
End If
Next
End Sub
With this code if the scrambled letters contain 'bok' then "book" will get selected. However removing the while loop and leaving only the remove statement, will ensure that only the exact number of each different letter will match. so that 'obok' will be needed to match "book".
As suggested by Steven Doggart, you have to invert the loop nesting. What you want is going through all the dictionary entries and, for each of them, checking if it contains all the letters in the string. Your loop structure is not allowing to do that.
I have performed the required updates in your code. Bear in mind that this code ignores caps ("A" is the same than "a").
Private Sub btnAnswers_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim hash As List(Of String) = New List(Of String)(System.IO.File.ReadAllLines("C:\Users\Katie\Documents\Project\dictionary.txt"))
Dim Letters As String = lblLetters.Text
For Each item As String In hash
Dim Found As Boolean = True
For i = 0 To Letters.Length - 1
Dim OneCharacter As String = Letters.Substring(i, 1)
Dim itemToLower As String = item.ToLower()
If Not itemToLower.Contains(OneCharacter.ToLower()) Then
Found = False
Exit For
End If
Next i
If (Found) Then
'The given dictionary entry includes all the letters in the label. No more iterations will be performed
MsgBox(item)
Exit For
End If
Next
End Sub
This code looks for keys containing all the characters in the given label (not at the contrary), that is: with a label "dict", "dictentry" would be right.
In any case, the whole point of my answer is not delivering a code which you just have to execute; the point of this code is helping you to understand what you did wrong and how to start doing things right. If you are not interested in this exact functionality, you woud have to edit my code such that what you want can be accomplished; or, ideally, you would be writing your own code completely from scratch.
You're calling MsgBox(item) outside of the if statement that determines whether the current word contains the current character. Which means it's going to pop up for every letter, every word. Move MsgBox(item) inside the first half of the if statement if you only want it to show when the letter is actually found in the word.
I'd also suggest following Steven Doggart's advice and reversing the way the loops are nested. If the characters are the outer loop, you could get the message box multiple times per word (e.g., if your letters are "sdf" and one of the words is "foods," it will pop up 3 times).
For Each item In hash
For i = 0 To Letters.Length - 1
OneCharacter = Letters.Substring(i, 1)
If item.Contains(OneCharacter) Then
Found = True
AllCharacters = OneCharacter
MsgBox(item)
Else
Found = False
End If
Next
Next

VB.NET AlphaNumeric into integer

If Textbox1.text contains a string value of ZU4, how can I convert that string to it's numeric ASCII codes, and output it to a second text box?
I'd like to do this using a FOR LOOP conditional statement which will read every character in INPUT?
Sample:
INPUT Textbox1.Text = ZU4
OUTPUT Textbox2.Text = 908552
You could also use LINQ:
TextBox2.Text = String.Join(String.Empty, From c In Textbox1.Text.ToCharArray Select (Asc(c).ToString))
Could be useful on some job interviews... :)
All of the other answers will work with your given example, however, some of the suggestions are using unicode encoding rather than ASCII. If strictly adhering to ASCII encoding is important, then you should explicitly specify the encoding that you want to use.
Convert.ToInt32 uses UTF-16 encoding. I'm not sure what CInt will do, but I suspect it works the same way. Using Asc is better, but it is still dependent on the code page setting for the thread, so it's still not entirely safe. Besides that, Asc is an old VB6 function which is provided in VB.NET, primarily for backwards compatibility.
Therefore, I would recommend using the ASCIIEncoding class instead. You can get an instance of that class using the shared ASCII property of the Encoding class in the System.Text namespace, for instance:
Public Function ConvertTextToAsciiDigits(text As String) As String
Dim builder As New StringBuilder()
For Each b As Byte In Encoding.ASCII.GetBytes(text)
builder.Append(b.ToString())
Next
Return builder.ToString()
End Function
Then, you can call the function like this:
Textbox2.Text = ConvertTextToAsciiDigits(Textbox1.Text)
However, I can't imagine that the resulting string will be usable unless every character results in a two digit number. Therefore, I would force it to be two digits by doing something like this:
Public Function ConvertTextToAsciiDigits(text As String) As String
Dim builder As New StringBuilder()
For Each b As Byte In Encoding.ASCII.GetBytes(text)
If b > 99 then
Throw New FormatException() ' Throws an exception if the value is three digits
End If
builder.Append(b.ToString("00")) ' Adds a leading zero to one-digit values
Next
Return builder.ToString()
End Function
To add a hyphen after every fourth digit, as you mentioned in a comment below, you could just keep track of the total digits added since the last hyphen, like this:
Public Function ConvertTextToAsciiDigits(text As String) As String
Dim builder As New StringBuilder()
Dim digitsSinceHyphen As Integer = 0
For Each b As Byte In Encoding.ASCII.GetBytes(text)
If b > 99 then
Throw New FormatException()
End If
builder.Append(b.ToString("00"))
digitsSinceHyphen += 2
If digitsSinceHyphen >= 4 Then
builder.Append("-")
digitsSinceHyphen = 0
End If
Next
Return builder.ToString()
End Function
Here is one approach, in C#:
Textbox2.Text = string.Empty;
foreach(var c in Textbox1.Text)
{
Textbox2.Text += ((int)c).ToString();
}
VB.NET:
Textbox2.Text = String.Empty
For Each c As Char In Textbox1.Text
Textbox2.Text = Textbox2.Text + Convert.ToInt32(c).ToString()
Next
It:
Clears out Textbox2.Text
Loops over each character in the input
Concatenates the integer value output as a string to the output text
TextBox2.Text = ""
For i As Integer = 0 To TextBox1.TextLength - 1
TextBox2.Text += Asc(TextBox1.Text(i)).ToString()
Next
i modified the code from this Link
Function AsciiEncode(ByVal value As String) As String
Dim encValue As New System.Text.StringBuilder(value.Length * 6)
Dim c As Char
For Each c In value
encValue.Append(Convert.ToInt32(c))
Next
Return encValue.ToString()
End Function
usage:
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
TextBox2.Text = AsciiEncode(TextBox1.Text)
End Sub