首页 > 解决方案 > 从 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; 
}

}

标签: javaarraylistfile-io

解决方案


JavaDoc 评论说:

@return 汽车的数组列表;如果遇到错误则返回 null

如果您null从 catch 块返回并cars在方法结束时,您将满足这些要求。

try {
    // read from file
}
catch (FileNotFoundException e) {
    // handle exception

    return null;
}

您可以在此处阅读有关从 catch 块返回的更多信息。


推荐阅读