java - 文件读取器直到最后才读取所有数据

标签 java linked-list java.util.scanner filereader

在 person.txt 中,我们存储了此人的详细信息。 好像是这样。

John
Smith
aösldkjf
5
8645
asdfasf
0441234545
++++++
Adam
Gilchrist
ads
asf
asf
asfd
0441234546
++++++

然后我们构建了 FileManager 类来从该文件中读取数据。 它标识有两个不同的条目。 但它总是读取前 8 行并且不继续前进。由于第一个人(例如:- John Smith)被添加到“LinkedList”中两次,命名为AddressBook。

//文件管理器类

public class FileManager {

    public static void readFile() {

        Scanner x;

        LinkedList<String> tempList = new LinkedList<String>();

        try {
            x = new Scanner(new File("Person.txt"));

            @SuppressWarnings("unused")
            String temp = null;

            while (x.hasNext()) {
                tempList.add(x.next());
                tempList.add(x.next());
                tempList.add(x.next());
                tempList.add(x.next());
                tempList.add(x.next());
                tempList.add(x.next());
                tempList.add(x.next());
                tempList.add(x.next());

                Person person = new Person();

                person.addFilePerson(tempList);

                Main.addressBook.add(person);

            }
        } catch (Exception e) {
            System.out.println("could't find the file");
        }
    }
}

//Person类中的addFilePerson方法

public void addFilePerson(LinkedList<String> list){

    vorname = list.get(0);
    nachname = list.get(1);
    strasse = list.get(2);
    hausnummer = list.get(3);
    plz = list.get(4);
    telefon = list.get(5);
    wohnort = list.get(6);
}

最佳答案

您正在创建一个 LinkedList<String>并反复添加。移动这一行:

LinkedList<String> tempList = new LinkedList<String>();

进入while环形。或者 - 并且最好是,IMO - 对不同部分使用单独的属性:

// TODO: Consider what happens if the file runs out half way through a person...
while (x.hasNext()) {
    Person person = new Person();
    person.setFirstName(x.next());
    person.setLastName(x.next());
    person.setStreet(x.next());
    person.setTown(x.next());
    person.setTelephoneNumber(x.next());
    person.setCity(x.next()); // Or whatever...

    Main.addressBook.add(person);
}

还有其他选项可以为Person创建“构建器”类型。并制作Person本身是不可变的,您可能想创建一个单独的 Address输入...

关于java - 文件读取器直到最后才读取所有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10106531/

相关文章:

java - 如何在 Java 项目中使用 Kotlin 编写的 MailChimp 包装器

java - spring 工具套件默认 mvc 项目 Web 应用程序

c - 链表元素在 for 循环中更新不佳

java - while 循环中的扫描仪输入验证

java - 如何在 Java 中使用 Scanner、while 和 for 循环来递增字符串名称

java - Android 运行时权限不断被拒绝

java - "The public type must be defined in its own file"但文件名和类名相同

java - 链接列表中的参数化类型

c++ - 如何交换链表 C++ 的索引

Java IO 无法读取文本文件