0

I know that this kind of question has already been treated on this forum, but I didn't find the correct answer I liked. I have a csv file with 2 columns, I'd like to compute the sum the the second column (value column) of my file. These are my csv file and my code example : file.csv

## Date ##     ## Value##
Status OK
12/12/2014          2
13/12/2014          5
14/12/2014          0
15/12/2014          3
Status KO
16/12/2014          5
17/12/2014          0
17/12/2014          7
17/12/2014          1

This class display just the column without the header (value). I like to make the sum of these elemnts (2+5+0+3+5+0+7+1)

public class LectureCSV {

public static void main(String[] args) {
    try {
        String csvFile = "C:/Users/Downloads/file.csv";

        @SuppressWarnings("resource")
        CSVReader csvReader = new CSVReader(new FileReader(csvFile), ';');
        String[] col;
        while ((col = csvReader.readNext()) != null) {
            if (!col[1].startsWith("valeur")) {
                System.out.println(col[1]);
            }

        }

    } catch (IOException ex) {
        Logger.getLogger(LectureCSV.class.getName()).log(Level.SEVERE,
                null, ex);
    }
}

}

2 Answers 2

1

If you're already printing the values, why not just keep a count and add to it rather than print.

When you reach the end you can just print the sum.

Sign up to request clarification or add additional context in comments.

2 Comments

thank you for your answer. now I can just print my column values. I didn't understand what you suggest. can you give me a peace of code please ?
Rather than call System.out.println, just add the value to a counter.
0

Thanks everybody, i've got the answer to my question. it was quite easy !

public class LectureCSV {

public static void main(String[] args) {
    try {
        String csvFile = "C:/Users/.../Downloads/file.csv";

        @SuppressWarnings("resource")
        CSVReader csvReader = new CSVReader(new FileReader(csvFile), ';');
        String[] col;
        float res = 0;
        while ((col = csvReader.readNext()) != null) {
            try {
                res = res + Float.parseFloat(col[1]);
            } catch (NumberFormatException e) {
            }
        }
        System.out.println(res);
    } catch (IOException ex) {
        Logger.getLogger(LectureCSV.class.getName()).log(Level.SEVERE,
                null, ex);
    }
}

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.