Computer Science Canada

Arrays

Author:  Master [ Fri May 21, 2004 4:03 pm ]
Post subject:  Arrays

how do you create an array with an undefined number of variables you want in the array

for ex. int[] a = new int[b]
what if i dont want to put "b" in and i want to have an undetermined amount

Thanks

Author:  da_foz [ Fri May 21, 2004 4:19 pm ]
Post subject: 

You can do two things.

1. You can declare the array but not instanciate it until you know

int [] a
...
//part of the program
...
a = new int[b] //where b is now known

2. You can use Vectors. What Vectors are is basicly a dynamic array. You have to be careful before Vectors can only take Objects (ie. an Integer and not an int).

I have to go out now, I will try to post more on Vectors a bit later.

Author:  Master [ Fri May 21, 2004 4:24 pm ]
Post subject: 

what i mean is that you use the arrary, but you will never know how many times you will use it
for example i have an asteroid program in which every time you press the space bar it should shoot out a fire(rectangle2d.double), if i keep pressing the space i want to have an unlimited number of shots.

Author:  Tony [ Fri May 21, 2004 4:29 pm ]
Post subject: 

Just see how many shots it's humanly possible to fire before they start going offscreen and that (+ a little buffer) would be your number. Then just recycle the array (such as when you use up the last element in the array, you know that the shot that was in the first element is long gone and the space is available for the next)

Author:  Master [ Fri May 21, 2004 4:57 pm ]
Post subject: 

how do you get rid of a section of an array or do you just reinitialize it?

and btw thanks

Author:  da_foz [ Fri May 21, 2004 7:23 pm ]
Post subject: 

tony wrote:
Just see how many shots it's humanly possible to fire before they start going offscreen and that (+ a little buffer) would be your number. Then just recycle the array (such as when you use up the last element in the array, you know that the shot that was in the first element is long gone and the space is available for the next)


You might run into a problem with different screen sizes and resolutions. If you can maximize the window then a bigger screen means you can have more 'shots' on at one time.

No, you do not have to reinitialize the array. When you want to do if you use tony's solution is determine your max number, then have a check if the array index you are at is max-1 (-1 because the array starts at 0). The way you will be referencing the array is by a counter. Each time you put something in the array you do counter + 1. When counter = max - 1, reset the counter to 0.

There might be a better way if we had more details. I don't understand why you want to store all of these in an array.


: