用Java探索CSV

问题描述 投票:0回答:1

我在Java上有一个任务:探索一个CSV与一些API我们有几个csv文件与namegenderNumber of Birth,首先是女孩,然后是男孩这样的。

First girls and then boys

有一个函数是我的老师给的。

private int getCsvRowOfMostPopularNameByGender(int year, String gender){
    int rank = -1;
    SEFileUtil seFileUtil = new SEFileUtil(getPathToCSV(year));
    for (CSVRecord record : seFileUtil.getCSVParser()) {
        String currGender = record.get(1);
        if (currGender.equals(gender)){
            rank = (int) record.getRecordNumber();
            break;
        }
    }
    return rank;
} // returning index of the First popular Name

现在我需要写一个函数来返回一个给定的名字的等级.我写了这个使用示例函数。

private int getRank (int year, String name, String sex ){

    SEFileUtil seFileUtil = new SEFileUtil(getPathToCSV(year));
    for (CSVRecord record : seFileUtil.getCSVParser()) {
        if (record.get(0).equals(name) && record.get(1).equals(sex)) {
            return (int) record.getRecordNumber() - getCsvRowOfMostPopularNameByGender(year,sex) + 1;
        }
    }
    return -1;
}

但后来我想自己找,我想直接在Csv文件的index i处访问对应的年份,并在classement超出范围的情况下返回-1.我试着声明新的对象类型CSVParser或CSVRecord,就像我们在for循环中使用的那样,但没有任何成功。

我认为我们使用的是apache的API.http:/commons.apache.orgpropercommons-csvjacocoorg.apache.commons.csvindex.source.html。http:/commons.apache.orgpropercommons-csvjacocoorg.apache.commons.csvindex.source.html。

java database csv oop
1个回答
0
投票

试试这样的东西

PS : 你应该考虑拆分你的代码1.读取数据并映射到一个合适的对象(1个csv行)2.处理你的数据。处理你的数据。

可读性是关键;)

private int getRow(int index) {

        SEFileUtil seFileUtil = new SEFileUtil(getPathToCSV(year));
        Iterable it = seFileUtil.getCSVParser();
        int i = 0 ;
        while ( it.hasNext() && i < index){
            it.next();
            index++;
        }
       if ( it.hasNext()){
           return it.next() ;
       }
       return ??
    }
© www.soinside.com 2019 - 2024. All rights reserved.