[英]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 eg 0 and 1 嗨,我下面有数组,我需要将内容复制到另一个一维数组中,但仅复制第一行,例如0和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. 坦白地说,由于foreach代码会创建一个计数器,因此最好使用山羊链接显示的循环类型。
The data contained in data[r][0]
is a String. data[r][0]
包含的data[r][0]
是字符串。 Not a String[]
(Array of Strings). 不是String[]
(字符串数组)。
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]
String[] codes = new String[data.lenght]
,然后将数据的[r] [0]元素分配给新创建的数组的第r个元素: codes[r] = data[r][0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.