i want to make a new variable that says shot1 shot2 shot3 so on and forth how do i do this? - vb.net

Here is what i have tried so far , but no new shot variable is being declared
Module Module1
Dim shotlist As New List(Of Boolean)
Dim shono As Integer = 0
Dim shonos As String
Dim shotname As String
Dim fshot As Boolean
Dim shots As String
Sub Main()
For i As Integer = 0 To 1000
Dim ("shots" & i) as String = "shots" & i
fshot = Convert.ToBoolean(shots)
Next
End Sub
End Module

You can't do things this way. The variable names you see when you write a program are lost, turned into memory addresses by the compiler when it compiles your program. You cannot store any information using a variable's name - the name is just a reference for you, the programmer, during the time you write a program (design time)
Think of variables like buckets, with labels on the outside. Buckets only hold certain kinds of data inside
Dim shotname as String
This declares a bucket labelled shotname on the outside and it can hold a string inside. You can put a string inside it:
shotname = "Shot 1"
You can put any string you like inside this bucket, and thus anything you can reasonably represent as a string can also be put inside this bucket:
shotname = DateTime.Now.ToString()
This takes the current time and turns it into a string that looks like a date/time, and puts it in the bucket. The thing in the bucket is always a string, and lots of things (nearly anything actually) can be represented as a string, but we don't type all our buckets as strings because it isn't very useful - if you have two buckets that hold numbers for example, you can multiply them:
Dim a as Integer
a=2
Dim b as Integer
b=3
Dim c as Integer
c=a*b
But you can't multiply strings, even if they're strings trust look like numbers; strings would have to be converted to numbers first. Storing everything as a string and converting it to some other type before working on it then converting it back to a string to store it would be very wearisome
So that's all well and good and solves the problem of storing varying information in the computer memory and giving it a name that you can reference it by, but it means the developer has to know all the info that will ever be entered into the program. shotname is just one bucket storing one bit of info. Sure you could have
Dim shotname1 as String
Dim shotname2 as String
Dim shotname3 as String
But it would be quite tedious copy paste exercise to do this for a thousand shotname, and after you've done it you have to refer to all of them individually using their full name. There isn't a way to dynamically refer to bucket labels when you write a program, so this won't work:
For i = 0 To 1000
shotname&i = "This is shotname number " & i
Next i
Remember, shotname is lost when compiling, and i is too, so shotname&i just flat out cannot work. Both these things become, in essence, memory addresses that mean something to the compiler and you can't join two memory addresses together to get a third memory address that stores some data. They were only ever nice names for you to help you understand how to write the program, pick good names and and not get confused about what is what
Instead you need the mechanism that was invented to allow varying amounts of data not known at the design-time of the program - arrays
At their heart, arrays are what you're trying to do. You're trying to have load of buckets with a name you can vary and form the name programmatically.
Array naming is simple; an array has a name like any other variable (what I've been calling a bucket up to now - going to switch to calling them variables because everyone else does) and the name refers to the array as a whole, but the array is divided up into multiple slots all of which store the same type of data and have a unique index. Though the name of the array itself is fixed, the index can be varied; together they form a reference to a slot within the array and provide a mechanism for having names that can be generated dynamically
Dim shotnames(999) as String
This here is an array of 1000 strings, and it's called shotnames. It's good to use a plural name because it helps remind you that it's an array, holding multiple something. The 999 defines the last valid slot in the array - arrays start at 0, so with this one running 0 to 999 means there are 1000 entries in it
And critically, though the shotnames part of the variable name remains fixed and must be what you use to refer to the array itself(if you want to do something with the entire thing, like pass it to a function), referring to an individual element/slot in the array is done by tacking a number onto the end within brackets:
shotnames(587) = "The 588th shotname"
Keep in mind that "starts at 0 thing"
This 587 can come from anything that supplies a number; it doesn't have to be hard coded by you when you write the program:
For i = 0 to 999
shotnames(i) = "The " & (i+1) & "th shotname"
Next i
Or things that generate numbers:
shotnames(DateTime.Now.Minute) = "X"
If it's 12:59 when this code runs, then shotnames(59), the sixtieth slot in the array, will become filled with X
There are other kinds of varying storage; a list or a dictionary are commonly used examples, but they follow these same notions - you'll get a variable where part of the name is fixed and part of the name is an index you can vary.
At their heart they are just arrays too- if you looked inside a List you'd find an array with some extra code surrounding it that, when the array gets full, it makes a new array of twice the size and copies everything over. This way it provides "an array that expands" type functionality - something that arrays don't do natively.
Dictionaries are worth mentioning because they provide a way to index by other things than a number and can achieve storage of a great number of things not known at design time as a result:
Dim x as New Dictionary(Of String, Object)
This creates a dictionary indexed by a string that stores objects (I.e. anything - dates, strings, numbers, people..)
You could do like:
x("name") = "John"
x("age") = 32
You could even realize what you were trying to do earlier:
For i = 0 to 999
x("shotname"&i) = "The " & (i+1) & "th shotname"
Next i
(Though you'd probably do this in a Dictionary(Of string, string), ie a dictionary that is both indexed by string and stores strings.. and you probably wouldn't go to this level of effort to have a dictionary that stores x("shotname587") when it's simpler to declare an array shotname(587))
But the original premise remains true: your variable has a fixed part of the name (ie x) and a changeable part of the name (ie the string in the brackets) that is used as an index.
And there is no magic to the indexing by string either. If you opened up a dictionary and looked inside it, you'd find an array, together with some bits of code that take the string you passed in as an index, and turn it into a number like 587, and store the info you want in index 587. And there is a routine to deal with the case where two different strings both become 587 when converted, but other than that it's all just "if you want a variable where part of the name is changeable/formable programmatically rather than by the developer, it's an array"

Related

Match Words and Add Quantities vb.net

I am trying to program a way to read a text file and match all the values and their quantites. For example if the text file is like this:
Bread-10 Flour-2 Orange-2 Bread-3
I want to create a list with the total quantity of all the common words. I began my code, but I am having trouble understanding to to sum the values. I'm not asking for anyone to write the code for me but I am having trouble finding resources. I have the following code:
Dim query = From data In IO.File.ReadAllLines("C:\User\Desktop\doc.txt")
Let name As String = data.Split("-")(0)
Let quantity As Integer = CInt(data.Split("-")(1))
Let sum As Integer = 0
For i As Integer = 0 To query.Count - 1
For j As Integer = i To
Next
Thanks
Ok, lets break this down. And I not seen the LET command used for a long time (back in the GWBASIC days!).
But, that's ok.
So, first up, we going to assume your text file is like this:
Bread-10
Flour-2
Orange-2
Bread-3
As opposed to this:
Bread-10 Flour-2 Orange-2 Bread-3
Now, we could read one line, and then process the information. Or we can read all lines of text, and THEN process the data. If the file is not huge (say a few 100 lines), then performance is not much of a issue, so lets just read in the whole file in one shot (and your code also had this idea).
Your start code is good. So, lets keep it (well ok, very close).
A few things:
We don't need the LET for assignment. While older BASIC languages had this, and vb.net still supports this? We don't need it. (but you will see examples of that still floating around in vb.net - especially for what we call "class" module code, or "custom classes". But again lets just leave that for another day.
Now the next part? We could start building up a array, look for the existing value, and then add it. However, this would require a few extra arrays, and a few extra loops.
However, in .net land, we have a cool thing called a dictionary.
And that's just a fancy term of for a collection VERY much like an array, but it has some extra "fancy" features. The fancy feature is that it allows one to put into the handly list things by a "key" name, and then pull that "value" out by the key.
This saves us a good number of extra looping type of code.
And it also means we don't need a array for the results.
This key system is ALSO very fast (behind the scene it uses some cool concepts - hash coding).
So, our code to do this would look like this:
Note I could have saved a few lines here or there - but that would make this code hard to read.
Given that you look to have Fortran, or older BASIC language experience, then lets try to keep the code style somewhat similar. it is stunning that vb.net seems to consume even 40 year old GWBASIC type of syntax here.
Do note that arrays() in vb.net do have some fancy "find" options, but the dictionary structure is even nicer. It also means we can often traverse the results with out say needing a for i = 1 to end of array, and having to pull out values that way.
We can use for each.
So this would work:
Dim MyData() As String ' an array() of strings - one line per array
MyData = File.ReadAllLines("c:\test5\doc.txt") ' read each line to array()
Dim colSums As New Dictionary(Of String, Integer) ' to hold our values and sum them
Dim sKey As String
Dim sValue As Integer
For Each strLine As String In MyData
sKey = Split(strLine, "-")(0)
sValue = Split(strLine, "-")(1)
If colSums.ContainsKey(sKey) Then
colSums(sKey) = colSums(sKey) + sValue
Else
colSums.Add(sKey, sValue)
End If
Next
' display results
Dim KeyPair As KeyValuePair(Of String, Integer)
For Each KeyPair In colSums
Debug.Print(KeyPair.Key & " = " & KeyPair.Value)
Next
The above results in this output in the debug window:
Bread = 13
Flour = 2
Orange = 2
I was tempted here to write this code using just pure array() in vb.net, as that would give you a good idea of the "older" types of coding and syntax we could use here, and a approach that harks all the way back to those older PC basic systems.
While the dictionary feature is more advanced, it is worth the learning curve here, and it makes this problem a lot easier. I mean, if this was for a longer list? Then I would start to consider introduction of some kind of data base system.
However, without some data system, then the dictionary feature is a welcome approach due to that "key" value lookup ability, and not having to loop. It also a very high speed system, so the result is not much looping code, and better yet we write less code.

Mid() usage and for loops - Is this good practice?

Ok so I was in college and I was talking to my teacher and he said my code isn't good practice. I'm a bit confused as to why so here's the situation. We basically created a for loop however he declared his for loop counter outside of the loop because it's considered good practice (to him) even though we never used the variable later on in the code so to me it looks like a waste of memory. We did more to the code then just use a message box but the idea was to get each character from a string and do something with it. He also used the Mid() function to retrieve the character in the string while I called the variable with the index. Here's an example of how he would write his code:
Dim i As Integer = 0
Dim justastring As String = "test"
For i = 1 To justastring.Length Then
MsgBox( Mid( justastring, i, 1 ) )
End For
And here's an example of how I would write my code:
Dim justastring As String = "test"
For i = 0 To justastring.Length - 1 Then
MsgBox( justastring(i) )
End For
Would anyone be able to provide the advantages and disadvantages of each method and why and whether or not I should continue how I am?
Another approach would be, to just use a For Each on the string.
Like this no index variable is needed.
Dim justastring As String = "test"
For Each c As Char In justastring
MsgBox(c)
Next
I would suggest doing it your way, because you could have variables hanging around consuming(albeit a small amount) of memory, but more importantly, It is better practice to define objects with as little scope as possible. In your teacher's code, the variable i is still accessible when the loop is finished. There are occasions when this is desirable, but normally, if you're only using a variable in a limited amount of code, then you should only declare it within the smallest block that it is needed.
As for your question about the Mid function, individual characters as you know can be access simply by treating the string as an array of characters. After some basic benchmarking, using the Mid function takes a lot longer to process than just accessing the character by the index value. In relatively simple bits of code, this doesn't make much difference, but if you're doing it millions of times in a loop, it makes a huge difference.
There are other factors to consider. Such as code readability and modification of the code, but there are plenty of websites dealing with that sort of thing.
Finally I would suggest changing some compiler options in your visual studio
Option Strict to On
Option Infer to Off
Option Explicit to On
It means writing more code, but the code is safer and you'll make less mistakes. Have a look here for an explanation
In your code, it would mean that you have to write
Dim justastring As String = "test"
For i As Integer = 0 To justastring.Length - 1 Then
MsgBox( justastring(i) )
End For
This way, you know that i is definitely an integer. Consider the following ..
Dim i
Have you any idea what type it is? Me neither.
The compiler doesn't know what so it defines it as an object type which could hold anything. a string, an integer, a list..
Consider this code.
Dim i
Dim x
x = "ab"
For i = x To endcount - 1
t = Mid(s, 999)
Next
The compiler will compile it, but when it is executed you'll get an SystemArgumenException. In this case it's easy to see what is wrong, but often it isn't. And numbers in strings can be a whole new can of worms.
Hope this helps.

Dynamically create variables in VB.NET

I have been trying to figure this out for some time now and can't seem to figure out an answer to it. I don't see why this would be impossible. I am coding in VB.NET.
Here is my problem:
I need to dynamically create variables and be able to reference them later on in the code.
More Details:
The number of variables comes from some math run against user defined values. In this specific case I would like to just create integers, although I foresee down the road needing to be able to do this with any type of variable. It seems that my biggest problem is being able to name them in a unique way so that I would be able to reference them later on.
Simple Example:
Let's say I have a value of 10, of which I need to make variables for. I would like to run a loop to create these 10 integers. Later on in the code I will be referencing these 10 integers.
It seems simple to me, and yet I can't figure it out. Any help would be greatly appreciated. Thanks in advance.
The best way to do something like this is with the Dictionary(T) class. It is generic, so you can use it to store any type of objects. It allows you to easily store and retrieve code/value pairs. In your case, the "key" would be the variable name and the "value" would be the variable value. So for instance:
Dim variables As New Dictionary(Of String, Integer)()
variables("MyDynamicVariable") = 10 ' Set the value of the "variable"
Dim value As Integer = variables("MyDynamicVariable") ' Retrieve the value of the variable
You want to use a List
Dim Numbers As New List(Of Integer)
For i As Integer = 0 To 9
Numbers.Add(0)
Next
The idea of creating a bunch of named variables on the fly is not something you are likely to see in any VB.Net program. If you have multiple items, you just store them in a list, array, or some other type of collection.
'Dim an Array
Dim xCount as Integer
Dim myVar(xCount) as String
AddButton Event . . .
xCount += 1
myVar(xCount) = "String Value"
'You will have to keep Track of what xCount Value is equal to to use.
'Typically could be an ID in A DataTable, with a string Meaning

Sorting 2 arrays side by side

Basicly I have a program that retrieves data and parses it, which is fine, so it starts from:
11:981.8 which equals to November 981.8 now what I have done is split the "November" and the "981.8" into 2 different arrays, with other similar data, now what I need to be able to do, is sort the array in either Ascending or Descending order, however keeping in tact, the November and 981.8 side by side in a list box.
My current code is:
Private Sub sortData(ByVal strYear As String, ByVal strSort As String)
lbDispData.Items.Clear()
Dim strData As String = My.Settings.usage2011
Dim arrRawData() As String
Dim arrMonth As New ArrayList
Dim arrKilo As New ArrayList
arrRawData = strData.Split("_")
For Each strUsage As String In arrRawData
Dim arrSmall As String()
arrSmall = strUsage.Split(":")
arrSmall(0) = MonthName(arrSmall(0))
arrMonth.Add(arrSmall(0))
arrKilo.Add(arrSmall(1))
Next
If strSort = 0 Then
'Sort in ascending order
ElseIf strSort = 1 Then
'Sort in descending order
End If
End Sub
Or If possible is there a better way?
EDIT: Just to mention, there are many more values, not just November and 981.8, there would be for example December and 128.1, January and 191.1, etc.
Don't use two arrays. Use one array or List, and each item in the array should be either an instance of a custom Class which would have Month and Kilo properties, or a Tuple instance.
Then you can sort by whichever property you want, and don't have to worry about related information staying together.
To create a Tuple for an item, you use Tuple.Create:
Dim myTuple = Tuple.Create(monthValue, kiloValue)
Then you can access values from the Tuple using Item1, Item2, etc.
Dim month = myTuple.Item1
Dim kilo = myTuple.Item2
There are essentially two ways to store this kind of data: array of structures, or structure of arrays. Your implementation, at present, is the latter. As you suspect, the former is typically preferred in languages which provide access to objects and user-defined types.
To solve this problem using an array-of-structures data representation, you will define your own type - for instance, you could call it MonthFloatPair or something more relevant to your application, or you could simply use a built-in type that suits your needs - and have a single array of type MonthFloatPair. To add a MonthFloatPair, you'd parse a string exactly as you are now, and then simply assign the month to one member of MonthFloatPair and the number (Kilo?) to another. Then all you would have to do is to write a method to provide an ordering comparison of MonthFloatPair objects (I believe this is possible in vb.net, at any rate), and then sort this array normally however you'd like.
To solve this problem using a structure-of-arrays data representation, you do exactly what you're doing now. To sort, sort normally as you would for the array you're sorting on, with one caveat: every time you change the position of an element of the array on which you're basing the sorting (e.g., by exchanging in O(n^2) sorts, or placing into a new array as in MergeSort), you need to move the corresponding (same index) element in the other array in the same manner.

VB .NET - how can I create an array of references to doubles?

I have a bunch of type Double variables in my program, say for example
Dim Area as Double = 0
Dim Perimeter as Double = 0
Somewhere in my program I want to calculate these values, so I define
Public Sub TheSquare(ByRef TheArea as Double, ByRef ThePerim as Double, ByVal TheSide as Double)
TheArea = TheSide^2
ThePerim = 4 * TheSide
End Sub
and somewhere in the program I'm collecting side lengths and calculating the area and perimeter; say
While True
S = GetSideValueFromSomewhere()
TheSquare(Area, Perimeter, S)
End
In my real program, I have, say, 20 quantities that I want to calculate. Obviously each one has a different equation. But in the end I want to output all 20 to a file, so to save typing, I create an array of the quantities, like this:
Dim TypingSaver() as Double = {Area, Perimeter}
so that I can dump values to file with a three-line for-loop instead of copying and pasting 20 variable names.
This does exactly what I want if Area and Perimeter were reference types like Objects. But since they are Doubles, TypingSaver contains only their values, not references to the actual variables. So after I use my TheSquare function the values of Area and Perimeter are correctly updated but TypingSaver just constains whatever the values of Area and Perimeter were when I declared the array.
So the question is: how can I create an array of references to doubles in VB.NET?
With approach that you are doing you can't do this, since as soon as you created array you copied all variables to the array and any changes that you are doing on variables are not reflected on array variables (like you pointed out).
What I would recommend create another class that will contain all your variables (20 variables name) as properties (get and set) and then override ToString method which will return list of all your variables. So when you need to dump those variables you will call ToString() method and it will return current values of all your parameters.
There is a nasty way to do this. All numeric types are value types, but arrays are reference types. So I can change all my Doubles to arrays of doubles, like this:
Dim Area(0) as Double
Dim Perimeter(0) as Double
So now Area and Perimeter are 1-element arrays of double. My "looping array" then becomes
Dim TypingSaver() as Array = {Area, Perimeter}
Now TypingSaver stores references to Area and Perimeter. For me this was an easy change because I could search-and-replace for the Double declaration, change the type for TypingSaver, then in two other places I had to change direct access of this form:
TypingSaver(1) = 7
to
TypingSaver(1).SetValue(7, 0)
Not pretty, but it keeps my code consistent in that I have other "looping arrays" for other objects that are all related to each other.
Although it is not clear in my question the real solution is to restructure everything so instead of storing everything in arrays I crate a class which has all the objects I need and create a single array of that, as suggested in part by Blezden.
The single-element array idea was actually terrible. The code became horrendously slow. There is another work around a friend suggested: create a wrapper class like this:
Public Class DoubleWrapper
Public Value As Double
End Class
Then when an array of DoubleWrappers is created it will be by reference, of course.
I understand this is not ideal but what I was looking for was a workaround until I have the time to rewrite the code from scratch.
Fairly similar to your most recent answer, you'll want to wrap your types as "Nullable", which basically makes it an object that could be null, but also a reference type.
Ie. Dim testDouble as Nullable(Of Double) or Dim testDouble2 as Double?
See:
Nullable(Of T) Structure - MSDN
What is the integer reference type in C#?