【问题标题】:How to store user Input temporarily in an arraylist and then store them permanently in a file (Java)如何将用户输入临时存储在数组列表中,然后将它们永久存储在文件中(Java)
【发布时间】:2021-07-05 17:55:08
【问题描述】:

我有一个名为 (Person) 的类,它获取所有用户信息并进行一些计算。 无论如何,我的问题是我想暂时将用户信息存储在 ArrayList 中,并且 然后永久保存在文件中。但我实际上无法存储它们

ArrayList<Person> info = new ArrayList<>();
    System.out.println("What is Your Name ? ");
    person.setName(input.nextLine());
    System.out.println("Please Enter Your Age: ");
    person.age = input.nextInt();
    System.out.println("Please Enter Your Weight: ");
    person.weight = input.nextInt();

如您所见,年龄和体重是 (Person) 类中的公共字段,而姓名是私有字段 为什么我使用 setName 方法。那么如何才能将这 3 个信息仅存储到 ArrayList 中,然后存储到 File 中呢?

谢谢

【问题讨论】:

    标签: java arrays file arraylist input


    【解决方案1】:
    1. 创建Person 的实例
    2. 填充person 的字段
    3. person 添加到列表中。
    final int ENOUGH = 10;
    ArrayList<Person> info = new ArrayList<>();
    
    while (true) {
        Person person = new Person();
        System.out.println("What is Your Name ? ");
        person.setName(input.nextLine());
        System.out.println("Please Enter Your Age: ");
        person.age = input.nextInt();
        System.out.println("Please Enter Your Weight: ");
        person.weight = input.nextInt();
    
        info.add(person);
    
        System.out.println("Type 0 to continue");
        boolean userWantsOut = input.nextInt() != 0;
        // check user input OR size of the list for exit condition and break
        if (userWantsOut || info.size() == ENOUGH) {
            break;
        }
    }
    

    至于将列表保存到文件中,这个问题太宽泛了,至少需要指定应该写入哪种类型的文件:文本(纯文本、CSV、JSON 等)或二进制(使用 ObjectOutputStream、JSONB等)

    【讨论】:

    • 非常感谢!这真的很有帮助。对于文件,它应该写为纯文本。再次非常感谢
    猜你喜欢
    • 2020-11-20
    • 1970-01-01
    • 1970-01-01
    • 2022-12-31
    • 1970-01-01
    • 2014-06-04
    • 1970-01-01
    • 2023-01-17
    • 1970-01-01
    相关资源
    最近更新 更多