【问题标题】:How to add items to an ArrayList in Java directly from a file?如何直接从文件中将项目添加到 Java 中的 ArrayList?
【发布时间】:2014-08-02 18:12:04
【问题描述】:

这似乎很容易,但我无法做到,尽管我是在 C# 中做到的。 为了这个例子,我会保持简单。 我有一个Person 类,字段为nameage。我有构造函数、getter 和 setter。

在我的主类中,我想从文件中读取数据并创建一个Person 对象,该对象将被添加到ArrayList。这是代码中似乎无法正常工作的部分。我使用了调试器并看到读数是正确的,我的文本文件的每一行都在 p 变量中的某个位置,但是当我打印它时,它只显示文件中的最后一个人 x 次(其中 x 是档案人数)。我使用了i 变量,因为我在网上查看并看到.add 有重载。第一次我只尝试了lst.add(p),第二次我使用i 变量来指定i 希望我的人在哪个位置。

File f = new File("fisier.txt");

    try{
        Scanner scn = new Scanner(f);
        int i = 0;
        while(scn.hasNext()){
            p.nume = scn.next();
            p.varsta = scn.nextInt();
            lst.add(i,p);
            i++;
        }
        scn.close();

    } catch(FileNotFoundException e){
        e.printStackTrace();
    }
    for(Persoana a : lst)
        System.out.println(a.nume + " " + a.varsta);
}

【问题讨论】:

    标签: java file arraylist


    【解决方案1】:

    您需要在循环中创建Person 的新实例:

    while(scn.hasNext()) {
        String name = scn.next();
        int age = scn.nextInt();
        Person p = new Person(name, age);
        lst.add(p); // simply add to the end of the list
    }
    

    【讨论】:

    • 好的。我现在试过了,它奏效了。我忘了我每次都要结交一个新人,现在我觉得问这样的问题很糟糕。感谢您的快速响应。
    【解决方案2】:

    每次Scanner 读取一个新值时,您使用的是同一个对象,因此每次您能够获取新值时都需要创建一个新的Person 对象。

    例如

    while(scn.hasNext()){
        int age = scn.next();
        String name = scn.nextInt();
        Person p = new Person(name, age);
        lst.add(p);
     }
    

    【讨论】:

      【解决方案3】:
      while(scanner.hasNext()) 
      {
        String name = scanner.next();
        int age = scanner.nextInt();
        Person person = new Person(name, age);
        list.add(person);
      }
      

      创建一个 Person 的实例。

      【讨论】:

        猜你喜欢
        • 2016-09-22
        • 2017-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-05
        相关资源
        最近更新 更多