繁体   English   中英

从CSV文件读取到对象

[英]Reading from a CSV file into Objects

我需要读取文件的帮助:我的文件看起来像这样:

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

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

默认的患者构造函数为每个对象创建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。 如果有人可以帮助我,我将不胜感激! 谢谢!

bufferedReader工作方式是分别解析每一行。 这就是您在String nextLine = br.readLine()情况下所做的-每次都读取一个新行。

使用CSV文件时,您仅阅读了第一行2, 您收到NoSuchElementException的原因是第一行上没有其他内容。 标记生成器无法为当前字符串找到其他任何内容。 您必须更改解析输入的方式,或者在继续之前读入下一行。

语法错误:

Integer.praseInt(st.nextToken());

....应该parse

for (int j=0 ....

失踪;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM