从另一个数组的每个第5个元素创建一个2D数组

时间:2015-05-11 13:08:37

标签: java arrays parsing multidimensional-array

好吧,我撞到了一堵砖墙,已经杀了我两天了,我的想法不合时宜。基本上我所拥有的是一个使用公司API从服务器接收数据的程序。数据恢复正常,我可以把它变成一个没有问题的数组。但是,我需要的是根据此数组中的值创建的辅助数组。让我告诉你:

Data Recieved and Parsed into Array:
String[] tag data = {d1,d2,d3,d4,d5,d6,d7,d8,d9,d10}  <-----these are populated automatically by the program. 

我需要的是另一个由d1-d5然后d6-d10创建的数组,我试过循环等等但问题是它只重复打印前五个。

这是我到目前为止的代码:

String[][] tags = null;

try {
    //Data is a string var that is passed to this method.It is the return data from the URL. 
    data = data.substring(61, data.length());
    String[] tagname = data.split(";");
    String[] secondArray = new String[5];
    for(int x = 0; x <= tagname.length; x++) {
        for(int i = 0; i <= 5; i++) {
            secondArray[i] = tagname[x];
        }
        tags[x] = secondArray;
    }
    Data.setTagArray(tags);
} catch(Exception e) {
    e.printStackTrace();
}

这是我收到的数据:

["Lamp_Status", null, null, null, null]
["Lamp_Status", 1, null, null, null]
["Lamp_Status", 1, 0, null, null]
["Lamp_Status", 1, 0, 0, null]
["Lamp_Status", 1, 0, 0, 654722]

我不需要特定的答案,我只需要帮助我们找到正确的方向。我不确定这里发生了什么,或者我怎么能做到这一点。再次回顾一下,我需要创建另一个数组的1-5,6-10个元素的数组。

2 个答案:

答案 0 :(得分:1)

你能试试吗

String[][] secondArray = new String[(tagname.length)/5][5];
for(int x = 0; x<=(tagname.length)/5; x++){
    for(int i = 0; i <= 5; i++)
        secondArray[x][i] = tagname[x]; 
}

答案 1 :(得分:0)

String[][] tags = null;

try {
    // Data is a string var that is passed to this method.It is the
    // return data from the URL.
    tags = new String[2][5];
    String[] tagname = {"d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "d10"};
    String[] secondArray = new String[5];

    tags[0] = Arrays.copyOfRange(tagname, 0, 5);
    tags[1] = Arrays.copyOfRange(tagname, 5, 10);
    System.out.println(Arrays.toString(tags[0]));
    System.out.println(Arrays.toString(tags[1]));
} catch(Exception e) {
    e.printStackTrace();
}

或复制您需要的范围。

相关问题