Importing data from .csv into array
Hello,
I'm trying to import a csv file into a 2D array and then find the average of each column. The csv file contains 3 columns each with 994 rows and consists entirely of doubles. I am very new to Java programming but have managed to write some code to read the file and populate an array. The problem I'm having is the data all seems to be in one column instead of three? I've done alot of research and can't figure out what is missing. My code so far is below. Any help would be greatly appreciated!
Thank you
Code java:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class csvimport {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
double [][] data = new double [994][2];
String line = null;
int row = 0;
int col = 0;
File file = new File("data.csv");
BufferedReader bufRdr = new BufferedReader(new FileReader(file));
//read each line of text file
while((line = bufRdr.readLine()) != null && row < 994)
{
StringTokenizer st = new StringTokenizer(line,",");
while (st.hasMoreTokens())
st.nextToken();
col++;
{
col=0;
}
{
String[] values = line.split(",");
for (String str : values) {
double str_double = Double.parseDouble(str);
data[row][col]=str_double;
System.out.println(str_double);
}
}
}
}
}
Re: Importing data from .csv into array
For future reference, please surround your code with the [highlight=java][/highlight] tags.
Not sure why you are using both StringTokenizer and split, which do redundant things. I'd say settle on using one. Further, when assigning data[row][col]=str_double;, I never see where row is incremented to assign the correct value to the correct row.
Re: Importing data from .csv into array
Many thanks for your quick reply, I really appreciate it. If I'm honest, I've only been programming for a few weeks as part of my engineering phd and so am a little new to some of the language. I understand what you mean about populating the array during parse so will try and amend my code and see if I can get it to work. I'll post once I've had a go.
Thanks again for your help
Re: Importing data from .csv into array
OK so I'm completely stumped! I can now read the data in OK and populate a 2D array with all the data in the correct place. The problem I've now got is that all the elements in the array are strings as oppose to doubles and I can't seem to get them to convert? Any ideas? Is there a better way of reading the data in so that it comes in as doubles rather than strings? Any help greatly appreciated - have been trying to get my head round this for 3 weeks now!!