Im probably going around this the wrong way, but My question is, how would I go about filling the array for fxRates?
CAD,EUR,GBP,USD
1.0,0.624514066,0.588714763,0.810307
1.601244959,1.0,0.942676548,1.2975
1.698615463,1.060809248,1.0,1.3764
1.234100162,0.772200772,.726532984,1.0
This is the information i have in the CSV file, I was thinking about using the scanner class to read it. Something like
private double[][] fxRates;
String delimiter = ","
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
fxRates = line.split(delimiter)
Your way of solving this problem seems OK. But
line.split(",")
will return a 1D String array. You cannot assign it tofxRates
. And also you should know the number of lines or rows in order to initializefxRates
at the beginning. Otherwise you should use a dynamic list structure likeArrayList
.Supposing you have 50 lines in your file, you can use something like:
And note that I've declared
fxRates
as a 2D String array, if you need double values you should do some conversion in place or later on.I wouldn't recommend you to parse CSVs in such a way, because
Scanner
is too low-level and raw solution for this. In comparison, DOM/SAX parsers are better to parse XML rather than regular expressions parsing or whatever that does not consider the document structure. There are CSV parsers that feature good APIs and suggest configuration options during a reader initialization. Just take a look at easy to use CsvReader. Here is a code sample using it:Another example;
The result of a
split
operation is aString
array, not an array ofdouble
. So one step is missing: converting the Strings to doubles: