Click to See Complete Forum and Search --> : How do you put objects into an array?
gjon
Nov 5th, 2006, 11:14 PM
If I had a couple regions that had multiple stores each. Is there a way to put these store objects into an array of a region?
I am trying things like:
static int size = 3;
static Region[] regions = new Region[size];
static void Main(string[] args)
{
//for (int k = 0; k < size; k++)
// regions[k] = new Region();
double[] stores = new double[5];
for (int k = 0; k < 5; k++)
stores[k] = IO.GetDouble("Enter the week's sales for store " + (k+1) + ": ");
regions[0] = stores;
with no luck. Thanks in advance for any help.
jmcilhinney
Nov 5th, 2006, 11:25 PM
Your 'stores' variable is a double array. You 'regions' variable is a Region array. You can't assign a double array to an element of a Region array. You can only assign a Region to an element of a Region array. If you want an array to hold an array of doubles then you need to declare a variable and create an array of that type:static double[][] regions = new double[5][];Now you have an array that can hold five double arrays.
gjon
Nov 5th, 2006, 11:49 PM
static double[][] regions = new double[5][];
So, to have 3 regions with 5 store sales shown would look something like?
regions = {{$200, $350, $450, $300, $250}, {$200, $350, $450, $300, $250}, {$200, $350, $450, $300, $250}};
jmcilhinney
Nov 6th, 2006, 12:07 AM
The code I posted creates a jagged array, which is an array of arrays. Specifically it creates an array that can contain 5 double arrays. What you've shown above is an array that contains 3 double arrays. The number specified is the number of arrays in the outer array, not the number of elements in the inner arrays. Not also that the reason that it's called a jagged array is because there is no requirement for each inner array to be the same same length. If what you actually want is a matrix where each element is a peer and all "rows" are the same length then you can use a two-dimensional array, which is different:static double[,] regions = new double[3,5];That now creates a two-dimensional array with 3 elements in one direction and 5 in the other. I'm not going to use the term rows and columns because there is no reason that any particular dimension is the rows and the other is the columns. Also, you can have arrays with many more dimensions than two if you want. Note that a two dimensional array is NOT the same as a jagged array. A jagged array is a one-dimensional outer array where each element is a one-dimensional array. A two-dimensional array is a single matrix where each element is a peer.
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.