簡體   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