I'm trying to read a CSV file and split each line into 4 different integer values via a two-dimensional array in java.
I'm using openCSV 3.8.
For the sake of simplicity, say this is the contents of the CSV file (the full file contains 306 lines just like these):
76,67,0,1
77,65,3,1
78,65,1,2
83,58,2,2
I can read the file just fine, and I can use System.out.println to output each single value to the console, like this:
76
67
0
1
77
65
3
1
78
65
1
2
85
58
2
2
Unfortunately with my code below, designed to enter each value into a separate array element only saves the 4 values in the last line of the file.
And here is my java code (don't mind the size of the iaData array, it's sized for the full CSV file):
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();
}
}
With this code, I would expect my System.out.println(iaData[0][z] + "\n"); to output the following to the console (the values in the first line of the file):
76
67
0
1
Unfortunately it's not the case, it actually outputs the following (the 4 values in the last line of the file):
83
58
2
2
What is wrong with my code such that iaData[0][0/1/2/3] actually outputs what I would expect to be held in iaData[**3**][0/1/2/3]?
For every line, you start writing with first index i=0. So for every line you override all information from the line before:
while ((nextLine = reader.readNext()) != null)
{
for (i = 0; i <= 305; i++)
{
for (x = 0; x <= 3; x++)
{
iaData[i][x] = Integer.parseInt(nextLine[x]);
}
}
}
This should solve your problem:
int i = 0;
while ((nextLine = reader.readNext()) != null) {
for (x = 0; x <= 3; x++) {
iaData[i][x] = Integer.parseInt(nextLine[x]);
}
i++;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With