【问题标题】:Exploring CSV with Java用 Java 探索 CSV
【发布时间】:2020-04-27 18:44:29
【问题描述】:

我有一个关于 Java 的作业:用一些 API 探索 CSV 我们有几个带有姓名/性别/出生人数的 csv 文件,首先是女孩,然后是男孩:

我的老师给了一个功能:

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 文件的索引 i 并在分类超出范围的情况下返回 -1。 我尝试像我们在 for 循环中使用的那样声明新的对象类型 CSVParser 或 CSVRecord,但没有任何成功

我认为我们正在使用 apach API:http://commons.apache.org/proper/commons-csv/jacoco/org.apache.commons.csv/index.source.html

【问题讨论】:

    标签: java database csv oop


    【解决方案1】:

    试试这样的

    PS:您应该考虑拆分代码 1. 读取数据并映射到合适的对象(每 csv 行 1 个) 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 ??
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-30
      • 2021-03-26
      • 1970-01-01
      • 2013-04-27
      相关资源
      最近更新 更多