我正在尝试读取CSV文件,并通过java中的二维数组将每一行拆分为4个不同的整数值.
我正在使用openCSV 3.8.
为简单起见,请说这是CSV文件的内容(完整文件包含306行,就像这些):
76,67,0,1
77,65,3,1
78,65,1,2
83,58,2,2
Run Code Online (Sandbox Code Playgroud)
我可以正常读取文件,我可以用来System.out.println将每个单独的值输出到控制台,如下所示:
76
67
0
1
77
65
3
1
78
65
1
2
85
58
2
2
Run Code Online (Sandbox Code Playgroud)
不幸的是,我的代码设计为将每个值输入到一个单独的数组元素中,只将4个值保存在文件的最后一行.
这是我的java代码(不介意iaData数组的大小,它的大小适合完整的CSV文件):
public static void main(String[] args) {
//String outputStr = "";
int[][] iaData = new int[306][4];
int i = 0;
int x = 0;
try
{
//Get the CSVReader instance with specifying the delimiter to be used
CSVReader reader = new CSVReader(new FileReader("haberman.data"),',');
String [] nextLine = new String[1250];
//Read one line at a time
while ((nextLine = reader.readNext()) != null)
{
for (i = 0; i <= 305; i++)
{
for (x = 0; x <= 3; x++)
{
iaData[i][x] = Integer.parseInt(nextLine[x]);
}
}
}
for (int z = 0; z <= 3; z++)
{
System.out.println(iaData[0][z] + "\n");
}
reader.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
使用此代码,我希望我System.out.println(iaData[0][z] + "\n");将以下内容输出到控制台(文件第一行中的值):
76
67
0
1
Run Code Online (Sandbox Code Playgroud)
不幸的是情况并非如此,它实际输出以下内容(文件最后一行中的4个值):
83
58
2
2
Run Code Online (Sandbox Code Playgroud)
我的代码有什么问题,iaData[0][0/1/2/3]实际上输出了我期望保留的内容iaData[**3**][0/1/2/3]?
对于每一行,您开始使用第一个索引i = 0进行写入.因此,对于每一行,您都会覆盖以前行中的所有信息:
while ((nextLine = reader.readNext()) != null)
{
for (i = 0; i <= 305; i++)
{
for (x = 0; x <= 3; x++)
{
iaData[i][x] = Integer.parseInt(nextLine[x]);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这应该可以解决您的问题:
int i = 0;
while ((nextLine = reader.readNext()) != null) {
for (x = 0; x <= 3; x++) {
iaData[i][x] = Integer.parseInt(nextLine[x]);
}
i++;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
233 次 |
| 最近记录: |