好吧,我碰壁了,这两天一直困扰着我,我没有主意了。基本上我拥有的是一个使用公司 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 创建的另一个数组,我已经尝试过 for 循环等,但问题是它只重复打印前五个。
这是我到目前为止的代码:
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 个元素的数组。
最佳答案
你可以试试吗
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];
}
关于java - 从另一个数组的每 5 个元素创建一个 2D 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30168533/