ethanqt ethanqt - 1 year ago 61
Java Question

Dealing with arrays as method results

So I've got this method:

public static int[] select(int maxWidth, int maxHeight) {
int rHeight = StdRandom.uniform(0, maxHeight);
int rWidth = StdRandom.uniform(0, maxWidth);
return new int[] {rHeight, rWidth};

And I'm not advanced enough to work with it on the right way.
I've got a second method where I want to execute 'select' several times. My idea was to do it with a for-loop like that (in which 'n' is a int):

for(int i = 0; i < n; i++){
select(h, w);

But now I don't know how to save the result from this for-loop in an 1d-array, since I will always get an error when trying to save like that:

int[] a = new int[select(h, w)];

I'm very aware that this looks very strange and wrong but I just don't know how to do it in the right way and I don't know for what I have to search on google.

Answer Source

Here is a way you could do it:

int[][] a = new int[n][];
for(int i = 0; i < n; i++){
   a[i] = select(h, w);

Basically this code creates a 2d array, then in the for loop, adds the result of select to each element of the array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download