views:

91

answers:

3

Hi all, Thanks for reading my question. I have a CSV file, I read it and store it in a variable. Now i just want to PLUS all the column to see its sum. For example

3,34
12,673
23,8543


SUM
-------------
965,12658

Columns and rows can be N limit. Looks easy but don't know, its taking my all time. Please do let me know which data structure should I use? Or if you can tell me some steps to solve this problem. Thanks !

+2  A: 

Since this is probably homework I won't give source code. You just need to read the lines and parse them using String.split. Convert them to integers using Integer.parseInt. Watch out for exceptions. If you have N columns you need to have N variables to hold the result. Update the variables after every read.

kgiannakakis
LOL, It is not an assignment. Also I did not ask for source code. I said if you can give me some hints. I am sorry but I couldn't understand your solution.I can read csv. I can split them i can store all values in variable. But declaring N variable for columns at runtime is not a practical solution. Yeah may be in school you can do this just to pass exam ;)
+3  A: 

First of all I recommend using this library to read the CSV: http://opencsv.sourceforge.net/

Using this library you could write something like this:

CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
String [] firstLine = reader.readNext();
long sum;
for (String columnValue : firstLine) {
    try {
        sum += Long.parseLong(columnValue);
    } catch (NumberFormatException e) {
        throw new RuntimeException(e);
    }
}
System.out.println(sum);

This example just reads the first line, but you could write a while-loop to keep parsing lines until the end of the file.

Tom van Zummeren
Sorry, I copied the wrong URL. I changed it to the correct one. Open CSV is the one you need.
Tom van Zummeren
thanks, It helped me to get the idea. I don't use opencsv when i can write my own program :)
A: 

Thank you all for your help. I solved it it by myself. I used 2 dimensional array. 1st represent column and 2nd represent rows. I get number of column to declare dynamic 1st array then used loop to store values and sum them ! ! !