copying 2dim array into 1 dim array
Hello
I would like to write a intance method called holdingColumn() which takes an int as an argument and returns a 1 dim int array called holdingArray of length 4.
This method will copy all the elements of a single column (column index indicated by the integar argument) of a 2 dim array called poolArray into holdingArray.
The method should then return holdingArray.
public void holdingColumn(int anInt)
int [][] poolArray = new int[4][3];
poolArray = new int [][] {{1,3,5},{7,9,11},{13,15,19},{21,23,25}};
int [][] holdingArray = new int[4][1];
for (int i = 0; i < 4;i++)
holdingArray[i][anInt] = poolArray [i][anInt];
I get this error when I run the program with any int other than 0.
Exception: line 3. java.lang.ArrayIndexOutOfBoundsException: 1
If I use public void holdingColumn() i.e without an argument and choose a specific column to copy as part of the method as follows:
public void holdingColumn()
int [][] poolArray = new int[4][3];
poolArray = new int [][] {{1,3,5},{7,9,11},{13,15,19},{21,23,25}};
int [][] holdingArray = new int[4][1];
for (int i = 0; i < 4;i++)
holdingArray[i][1] = poolArray [i][1];
then no problem the second column of poolArray gets copied into holdingArray.
I think it is because I have created a 2 dim array called holdingArray(albeit it is 1 dim), I do not another way I can copy elements of a 2dim array into 1 dim array.
Can you please advise on my method,
rgds av8.
Re: copying 2dim array into 1 dim array
Quote:
Originally Posted by
av8
a 1 dim int array called holdingArray
So why have you declared holdingArray as a 2D array?
Re: copying 2dim array into 1 dim array
I dont know the syntax to copy from a 2dim array into a 1dim array proper, so I created a 2 dim array which has only 1 dim if that makes sense.
Re: copying 2dim array into 1 dim array
The syntax is basically the same: copy the value at position x,y into position x. I assume you know how to access elements in an array.
Re: copying 2dim array into 1 dim array
Yes it works with and also with an int as argument aswell ! Thanks and what line of code would I add to the end of my method to return holdingArray?
Re: copying 2dim array into 1 dim array
Re: copying 2dim array into 1 dim array
Yes it works with and also with an int as argument aswell ! Thanks and what line of code would I add to the end of my method to return holdingArray?
Re: copying 2dim array into 1 dim array
Re: copying 2dim array into 1 dim array
junky is right, change your holding array to int [] holdingArray = new int[4];
then your transfer line should look like holdingArray[i]=poolArray[i][1];
that way your taking a single int from the position you want to, tell me if this helps