簡體   English   中英

從Java中的特定csv列計算數據

[英]Compute data from a specific csv column in java

我知道這個問題已經在這個論壇上得到了解決,但是我沒有找到我喜歡的正確答案。 我有一個包含2列的csv文件,我想計算文件第二列(值列)的總和。 這些是我的csv文件和代碼示例: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

此類僅顯示沒有標題(值)的列。 我喜歡將這些元素的總和(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);
    }
}

}

如果您已經在打印值,為什么不保留計數並添加到計數而不是打印。

當您到達末尾時,您可以只打印總和。

謝謝大家,我已經回答了我的問題。 這很容易!

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);
    }
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM