我有一个关于 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。 我尝试声明新的对象类型 CSVParser 或 CSVRecord 就像我们在 for 循环中使用的那样,但没有成功
我认为我们正在使用 apache API:http://commons.apache.org/proper/commons-csv/jacoco/org.apache.commons.csv/index.source.html
最佳答案
尝试这样的事情
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 ??
}
关于java - 使用 Java 探索 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61466119/