开发者

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


Try this:

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

That should work


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.


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]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜