gpt4 book ai didi

java - 在 Java 中读取文本文件并将其添加到对象的 ArrayList 中

转载 作者:行者123 更新时间:2023-12-01 12:10:25 26 4
gpt4 key购买 nike

我有一个文本文件“addresses.txt”,其中包含有关某人的信息。我创建了一个 Person 类,我需要读取该文本文件中的信息并将其存储到 ArrayList 中。我的错误是,当尝试读取文本文件时,由于字符串争论,我无法将其添加到我的 ArrayList 中。此时我真的迷失了,我知道这可能是一个简单的解决方案,但我就是想不通。

如果需要的话,这是我的一些 Person 类:

public class Person {
private String firstName;
private String lastName;
private String phoneNumber;
private String address;
private String city;
private String zipCode;

private static int contactCounter = 0;

public Person(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
contactCounter++;
}

public Person(String firstName, String lastName, String phoneNumber){
this.firstName = firstName;
this.lastName = lastName;
this.phoneNumber = phoneNumber;
contactCounter++;
}

public Person(String firstName, String lastName, String address, String city, String zipCode){
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.city = city;
this.zipCode = zipCode;
contactCounter++;
}

这是我的主要类(class):

import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
public class Rolodex {

public static void main(String[] args) {
ArrayList <Person> contactList = new ArrayList <Person> ();
readFile(contactList);
}

public static void readFile(ArrayList <Person> contactList){
try{
Scanner read = new Scanner(new File("addresses.txt"));
do{
String line = read.nextLine();
contactList.add(line); //MY ERROR IS HERE. I know why its happening just not how to fix.
}while(read.hasNext());
read.close();
}catch(FileNotFoundException fnf){
System.out.println("File was not found.");
}
}

最佳答案

您尝试将字符串行添加到 Person 数组中。您无法将 String 强制转换为 Person。修复:尝试实现某种行解析器例如。您的行看起来像这样 "adam;bra;555888666;" 您必须使用 line.split(";") 解析此字符串它会创建字符串数组(String[]),现在只需使用构造函数来创建 Person 并将其添加到 contactList 中例如。

contactList.add(New Person(parsedString[0], parsedString[1], parsedString[2]));

关于java - 在 Java 中读取文本文件并将其添加到对象的 ArrayList 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27311909/

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