gpt4 book ai didi

java - 根据文件内容创建对象数组

转载 作者:行者123 更新时间:2023-11-30 08:49:33 25 4
gpt4 key购买 nike

我有一个看起来像这样的文本文件。

BEGINNING OF LIST

Name: Janet
Age: 21
Birthday month: April

END OF LIST

BEGINNING OF LIST

Name: Peter
Age: 34
Birthday month: January

END OF LIST

所以我想获取信息并将其放入一个对象数组中。这是一个广泛的列表,我使用分隔符 beginning of listend of list 来分隔内容。

如何将这些项目存储在对象数组中?

最佳答案

我建议您先创建一个类来存储信息,其中包含nameagebirthday month 属性。覆盖 toString() 方法是一个很好的做法,这样您就可以整齐地打印出类。

然后您可以通过将每一行拆分为一个单词数组并检查信息来检查每一行是否包含有关姓名、年龄或生日月份的信息。

一旦该行显示为“END OF LIST”,您可以将带有参数的 class Person 添加到 ArrayList

例如,我使用 “people.txt” 作为文件(确保将文本文档放在包含 .java 文件的 src 文件夹之外) .

主.java

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {

public static void main(String[] args)
{
BufferedReader bufferedReader = null;
FileReader fileReader = null;
String name = null;
String age = null;
String month = null;
List<Person> people = new ArrayList<Person>();

try
{
String fileName = "people.txt";
fileReader = new FileReader(fileName);
bufferedReader = new BufferedReader(fileReader);
String line = null;

while ((line = bufferedReader.readLine()) != null)
{
String[] information = line.split(" ");

if (Arrays.asList(information).contains("Name:"))
{
name = information[1];
}
if (Arrays.asList(information).contains("Age:"))
{
age = information[1];
}
if (Arrays.asList(information).contains("month:"))
{
month = information[2];
}
if (line.equals("END OF LIST"))
{
people.add(new Person(name, age, month));

name = "";
age = "";
month = "";
}
}

for (Person person : people)
{
System.out.println(person);
System.out.print("\n");
}
}
catch (FileNotFoundException e)
{
System.out.println(e.getMessage());
}
catch (IOException ex)
{
System.out.println("Error reading people.txt");
}
finally
{
if (bufferedReader != null)
{
try
{
bufferedReader.close();
}
catch (IOException ex)
{
System.out.println(ex.getMessage());
}
}
if (fileReader != null)
{
try
{
fileReader.close();
}
catch (IOException ex)
{
System.out.println(ex.getMessage());
}
}
}
}
}

Person.java

public class Person {
private String name;
private String age;
private String birthday;

public Person(String name, String age, String birthday)
{
this.name = name;
this.age = age;
this.birthday = birthday;
}

@Override
public String toString()
{
String information = "Name: " + name + "\nAge: " + age + "\nBirthday: " + birthday;
return information;
}
}

关于java - 根据文件内容创建对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31373823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com