我有一个用逗号分隔的值字符串,然后将其转换为数组,然后将其用于创建2D数组。创建循环以将数据从第一个数组添加到2D数组时,它正在重复数据。
我得到的输出是:
4428,40,401,610,2016,3821,31,347,572,2015,4381,38,341,520,2014,2536,17,193,290,2013,4295,39,371,552,2012,4643,45,343,502,2011,3922,28,312,475,2010,4434,30,350,541,2009 ,4038,28,341,536,2008,218,1,20,28,2007,46,0,6,15,2006,65,0,9,16,2005,4428,40,401,610,2016,3821,31,347,572,2015,4381 ,38,341,520,2014,2536,17,193,290,2013,4295,39,371,552,2012,4643,45,343,502,2011,3922,28,312,475,2010,4434,30,350,541,2009,4038,28,341,536,2008,218,1,20,28,2007 ,46,0,6,15,2006,65,0,9,16,2005,4428,40,401,610,2016,3821,31,347,572,2015,4381,38,341,520,2014,2536,17,193,290,2013,4295,39,371,552,2012 ,4643,45,343,502,2011,3922,28,312,475,2010,4434,30,350,541,2009,4038,28,341,536,2008,218,1,20,28,2007,46,0,6,15,2006,65,0,9 ,16,2005,4428,40,401,610,2016,3821,31,347,572,2015,4381,38,341,520,2014,2536,17,193,290,2013,4295,39,371,552,2012,4643,45,343,502,2011,392,2,28,312,475,2010,4434,30,350,541 ,2009,4038,28,341,536,2008,218,1,20,28,2007,46,0,6,15,2006,65,0,9,16,2005,4428,40,401,610,2016,3821,31,347,572,2015 ,4381,38,341 ,520,2014,2536,17,193,290,2013,4295,39,371,552,2012,4643,45,343,502,2011,3922,28,312,475,2010,4434,30,350,541,2009,4038,28,341,536,2008,218,1,20,28,2007 ,46,0,6,15,2006,65,0,9,16,2005
,正确的输出应为:
4428,40,401,610,2016,3821,31,347,572,2015,4381,38,341,520,2014,2536,17,193,290,2013,4295,39,371,552,2012,4643,45,343,502,2011,3922,28,312,475,2010,4434,30,350,541,2009 ,4038,28,341,536,2008,218,1,20,28,2007,46,0,6,15,2006,65,0,9,16,2005
预期结果:
{{4428,40,401,610,2016}
{3821,31,347,572,2015}
{4381,38,341,520,2014}
...}等,每5
我将数组添加到2D数组的代码如下:
{String[] columns = {"Yards","Touchdowns","Attempts","Incompletions","Year"};
String[] data1 = results1.split(",");
Object [][] data11 = new Object[columns.length][data1.length];
for(int i = 0; i<columns.length;i++){
for(int j = 0; j<data1.length;j++){
data11[i][j] = data1[j];
//System.out.print(data11[i][j]+",");
}
}}
编辑:解决方案!
Object [][] data11 = new Object[data1.length/columns.length][columns.length];
int column = -1;
for(int j = 0; j<data1.length;j++){
if(j % columns.length == 0) column = column+1;
data11[column][j % 5] = data1[j];
}
答案 0 :(得分:0)
您还循环了第一个数组(i),因此他将重复它。只需写下:
data11[0][j] = data1[j];
或者甚至根本不执行第一个循环,具体取决于您的需求。 假设您的输出是,您只想填充数组的第一个位置(0)。
答案 1 :(得分:0)
也许这对您有用:
Object [][] data11 = new Object[columns.length][data1.length / 5];
int column = -1;
for(int j = 0; j<data1.length;j++){
if(j % 5 == 0) column = column + 1
data11[j % 5][column] = data1[j];
}
请注意矩阵大小已更改,分配也已更改。尚未尝试过,也许您可以制作一个更漂亮的版本。希望对您有帮助!