Elliott
Elliott

Reputation: 3864

multidimensional array row to single array java

Hi I have the array below, I need to copy the contents into another single dimensional array but only the first row e.g. 0 and 1

String data[][] = new String[][]
   {
      {"0", "1", "2", "3", "4"},
      {"1", "1", "2", "3", "4"}
   }

The above code is an example of how I have set my array, I just need the first row but for every colum

I have tried:

for (int r = 0; r < data.length; r++)
   {
    codes = new String[]  {data[r][0]};
   }

But that doesnt work, any ideas? Thanks

Upvotes: 1

Views: 1050

Answers (3)

pmr
pmr

Reputation: 59841

The data contained in data[r][0] is a String. Not a String[] (Array of Strings).
What you want to do: create an array that has the same size as you have columns. String[] codes = new String[data.lenght] and then assign the [r][0] element of data to the r-th element of your newly created array: codes[r] = data[r][0]

Upvotes: 0

Tom Neyland
Tom Neyland

Reputation: 6968

Or try:

String[] codes = new String[data.length];
int i=0;
for(String[] strings : data)
{
    codes[i++]=strings[0];
}

Although honestly, since foreach code creates a counter, you may be better off using the type of loop that goatlinks showed.

Upvotes: 0

goatlinks
goatlinks

Reputation: 771

Try this:

String[] codes = new String[data.length];
for (int r = 0; r < data.length; r++) {
    codes[r] = data[r][0];
}

That should work

Upvotes: 1

Related Questions