我有一个包含对象的数组列表。每个对象包含许多字符串。我正在尝试获取这些字符串并将它们添加到二维数组中。
public void iterateRow(Row row)
{
int x = 0;
int y = size();
tableArray = new String[y][5];
while(x < y){
int z = 0;
for (String s: row.rowString()){
tableArray[x][z] = s;
z++;
}
x++;
}
}
每当我运行并为行类创建一个新实例时,该方法应该将 Row 中包含的字符串添加到数组中。但是它会将最新条目复制 x 次(其中 x 是条目总数)。
这里是 Row 类以供进一步引用:
public class Row
{
public String appNumber;
public String name;
public String date;
public String fileLoc;
public String country;
public String elementString;
public String results[];
public Row(String appNumber, String name, String date, String fileLoc, String country, Table table)
{
this.appNumber = appNumber;
this.name = name;
this.date = date;
this.fileLoc = fileLoc;
this.country = country;
table.addApplicant(this);
}
public String[] rowString()
{
String[] a = {appNumber, name, date, fileLoc, country};
return a;
}}
我认为这是 iterateRow() 方法中的一个愚蠢的逻辑错误,但我似乎无法弄清楚是什么。任何帮助将不胜感激。
编辑:在大家的帮助下,我删除了 while 循环。然而,它似乎仍然在复制行而不是移动到下一行?
public void iterateRow(Row row)
{ int x = 0;
int y = size();
tableArray = new String[y][row.rowString().length];
for(int i =0; i<y;i++){
int z = 0;
for (String s: row.rowString()){
tableArray[x][z] = s;
z++;
}x++;}
}
最佳答案
问题看起来是在 while 循环中。例如,如果 size() 返回 3,则 while 循环将以 x=0,1,2 执行,因此您将分配 tableArray[0],然后是 tableArray[1],然后是 tableArray[2]。
很难说出解决方案是什么,因为我根本不明白为什么代码中有 while 循环。
关于java - 用于添加到二维数组的 while 和 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15368609/