java - 从 CSV 文件中读取数组
问题描述
(编辑,更新代码)我正在尝试完成从 CSV 文件中读取数组并返回汽车数组列表的任务。我通过了五个测试中的两个,但我认为我的问题是最后的“返回 null”。我不确定我应该返回什么。我试过翻阅我们的讲义并问过教授,他们都没有帮助。我不是在要求答案,我只需要指出正确的方向
到目前为止,这是我的代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
/**
* Practice reading CSV files
*
* @author 250 Instructors
* @version Feb 2017
*
*/
public class CarsForSale {
/**
* Read an array from CSV file
*
* @param aFile
* - string pointing to file
* @return the array list of Cars; return null if error encountered
*/
public static ArrayList<Car> getCarsFromCSVFile(String aFile) {
ArrayList<Car> cars = new ArrayList<Car>();
File file = new File(aFile);
try {
Scanner scan = new Scanner(file);
while (scan.hasNext()) {
String car = scan.nextLine();
}
scan.close();
}
catch (FileNotFoundException e) {
System.out.println("Failed to open file " + aFile);
System.out.println(e);
return null;
}
return cars;
}
}
解决方案
JavaDoc 评论说:
@return 汽车的数组列表;如果遇到错误则返回 null
如果您null
从 catch 块返回并cars
在方法结束时,您将满足这些要求。
try {
// read from file
}
catch (FileNotFoundException e) {
// handle exception
return null;
}
您可以在此处阅读有关从 catch 块返回的更多信息。
推荐阅读
- python - 在 K-Means 聚类之后绘制聚类
- graphics - 使用 Nvidia 驱动程序运行 Intel GPU 工具
- android - 如何在谷歌照片中为应用程序提供多个共享选项?
- python - Python生成器在应该提供的时候没有提供yield
- rx-java - 如何在 RxJava 中仅获取 zip 的最后一个值?
- reactjs - React:如何在渲染之前处理从 API 获得的数据?
- php - 有没有办法在 Laravel 5.5 中更改 url?
- regex - 为什么不能在 oracle 中将 ']' 的字符与 regexp_like 匹配?
- python - 将数据框从 Python 写入 html 时修复表头
- java - org.hibernate.property.access.spi.PropertyAccessException:访问字段时出错 [private java.lang.String,