我正在尝试读取这样的CSV文件:
1,0,0,0,2,0,0,2,
0,2,0,0,0,0,0,5,
0,0,0,0,0,0,5,0,
这是我的预期结果:
[1, 5, 8]
[2, 8,]
[7]
这是我的Java编码:
CSVReader a = new CSVReader(new FileReader("CM.csv"));
List<String[]> aa = a.readAll();
List<Integer> list = new ArrayList<>();
Object[] CM = new Object[3];
for (int i = 0; i < aa.size(); i++) {
for (int x = 0; x < aa.get(i).length-1; x++) {
if ( Integer.parseInt(aa.get(i)[x].trim()) >= 1 ){
list.add(x+1);
}
}
CM[i] = list;
list.clear();
}
for (int i = 0; i < CM.length; i++) {
System.out.print(CM[i]);
System.out.print("\n");
}
但我得到了Null的结果。如果我删除list.clear()行,那么得到奇怪的结果:
[1, 5, 8, 2, 8, 7]
[1, 5, 8, 2, 8, 7]
[1, 5, 8, 2, 8, 7]
我想将列表存储到数组中,请忽略我读取CSV文件的方式...
答案 0 :(得分:1)
将list.clear();
替换为list = new ArrayList<>();
您正在为CM [i]分配列表,当您调用list.clear()时,它会清除列表并使其成为空列表,因为您的CM变量指的是列表对象,它不会包含任何值。
获取值:
for (int i = 0; i < CM.length; i++) {
List dataList = (List) CM[i];
for (int j = 0; j < dataList.size(); j++) {
// do your stuff
System.out.println(dataList.get(j));
}
}
答案 1 :(得分:1)
public class Location {
private int x = 0;
private int y = 0;
public Location(int x, int y)
{
this.x = x;
this.y = y;
}
public int getX()
{
return this.x;
}
public int getY()
{
return this.y.
}
}
CSVReader csvReader = new CSVReader(new FileReader("CM.csv"));
List<String[]> records = csvReader.readAll();
ArrayList<Location> locations = new ArrayList<Location>();
for(int i = 0; i < records.size(); i++)
{
for(int j = 0; j < records.get(i).length; j++)
{
if(Integer.parseInt(records.get(i)[j]) > 0)
{
locations.add(new Location(i,j));
}
}
}
现在,您所有的位置都将存储在arraylist的位置。您所要做的就是遍历它并获取记录arraylist的坐标。