【问题标题】:Reading from a CSV file into Objects从 CSV 文件读入对象
【发布时间】:2013-11-20 23:19:50
【问题描述】:

我需要帮助读取文件: 我的文件看起来完全一样:

2,
Bob,
1,
Hand, 10.0, Broken,
John,
Leg, 20.0, Broken,
Hand, 10.0, Broken, //this comma has to be here

我需要将此数据加载到存储 Bob 和 John 的数组中,并将伤害加载到 数组列表。

默认的患者构造函数为每个人创建 arrayList。

我的代码是这样的:

public void load(File f) {
    try {
        BufferedReader br = new BufferedReader(new File Reader(f));
        String nextLine = br.readLine();
        while (nextLine!=null) {
        StringTokenizer st = new StringTokenizer(nextLine, ",");
        int numberOfPatients = Integer.praseInt(st.nextToken());

        for (int j=0 j<numberOfPatients; j++) {
            String name = st.nextToken();   // This is the place where I get NoSuchElementException
            int age = Integer.parseInt(st.nextToken());
            this.patients[j-1] = new Patient(name,age);
            int numberOfInjuries = Integer.parseInt(st.nextToken());

            for (int i=0; i<numberOfInjuries-1; i++) {
                String type = (st.nextToken());

                if (type.equals("Leg")) {
                    int cost = Integer.parseInt(st.nextToken());
                    String injury = st.nextToken();
                    // addInjury - function to add new injury to the arrayList
                    this.patients[j].addInjury(new Leg(cost, injury));
                } else if (type.equals("Hand")) {
                    int cost = Integer.parseInt(st.nextToken());
                    String injury = st.nextToken();
                    this.patients[j].addInjury(new Hand(cost, injury);
                }
            nextLine = br.readLine();
        }
        br.close();
    } catch(Exception ex) {
        System.out.println(ex);
        System.exit(1);
    }
}

它返回 java.util.NoSuchElementException。 如果有人可以帮助我,我将不胜感激!谢谢!

【问题讨论】:

    标签: java arrays csv arraylist nosuchelementexception


    【解决方案1】:

    bufferedReader 的工作方式是单独解析每一行。这就是你在 String nextLine = br.readLine() 所做的事情——每次都换行。

    使用您的 CSV 文件,您只阅读了第一行 - 2,。您获得NoSuchElementException 的原因是第一行没有其他内容。标记器找不到当前字符串的任何其他内容。您要么必须更改解析输入的方式,要么在继续之前阅读下一行。

    【讨论】:

    • 此外,根据您的 for 循环的设置方式,您将尝试访问患者 [j-1]。 j(最初)为 0 时,您将尝试访问患者 [-1],这将中断。希望这会有所帮助
    • 我应该添加 nextLine = br.readLine();每当我想跳到下一行时?
    • 这行得通,但是你冒着 nextLine 为空的风险(特别是如果你正在处理一组未知的数据)。请确保在使用前检查它。
    • 它仍然无法正常工作,抛出同样的错误:/ 代码中是否还缺少其他内容?
    【解决方案2】:

    语法错误:

    Integer.praseInt(st.nextToken());
    

    ....应该是 parse

    for (int j=0 ....
    

    缺少;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-20
      • 1970-01-01
      • 2021-02-05
      • 1970-01-01
      相关资源
      最近更新 更多