繁体   English   中英

如何将用户输入临时存储在 arraylist 中,然后将它们永久存储在文件中(Java)

[英]How to store user Input temporarily in an arraylist and then store them permanently in a file (Java)

我有一个名为 (Person) 的 class,它获取所有用户信息并进行一些计算。 无论如何,我的问题是我想将用户信息暂时存储在 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) class 中的公共字段,而 Name 是私有字段,这就是我使用 setName 方法的原因。 那么如何才能将这 3 个信息仅存储到 ArrayList 中,然后存储到文件中呢?

谢谢

  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 等)。 )

暂无
暂无

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

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