简体   繁体   中英

Creating a 2D array from every 5th element of another array

Alright I have hit a brick wall and it has been killing me for two days and I am out of ideas. Basically what I have is a program that receives data back from a server using the companies API. The data comes back fine and I am able to turn it into an array without an issue. However, what I need is a secondary array created from values in this array. Let me show you:

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. 

What I would need is another array created by say d1-d5 and then d6-d10, I have tried for loops and whatnot but the problem is it only prints the first five repeatedly.

Here is the code I have so far:

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();
}

This is the data I get back:

["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]

I don't need a specific answer I just need help getting in the right direction. I am not sure what is going on here or how I can make this work. Once again to recap I need to create an array of 1-5, 6-10 elements of another array.

Can you try

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]; 
}
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();
}

Or copy the ranges you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM