gpt4 book ai didi

java - 代码仅将文本文件的一行保存到数组中

转载 作者:太空宇宙 更新时间:2023-11-04 07:55:08 24 4
gpt4 key购买 nike

我生成的代码旨在提供逐行读取文本文件并将每行保存到数组中的功能。它似乎可以正确读取每一行,但是当我使用 printProps() 方法时,它只显示一个...

代码仅将文本文件的一行保存到数组中,我的代码有什么问题?

/*reading in each line of text from text file and passing it to the processProperty() method.*/
Public void readProperties(String filename) {
try {
BufferedReader reader = new BufferedReader(new FileReader(filename));
int i = 0;
String line;
line = reader.readLine();
while (line != null && !line.equals("")) {
i++;
processProperty(line);
line = reader.readLine();
}
System.out.println("" + i + " properties read");
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();

}
}

/*Breaks up the line of text in order to save the value to an array (at this point it only saves one line to the array). org.newProp(newProp) passes the new property to the Organize class where it saves it to an array.

public void processProperty(String line) {
org = new Organize();
int id = nextPropertyID;
nextPropertyID++;

String[] parts = line.split(":");
int propNo = Integer.parseInt(parts[0]);
String postcode = parts[1];
String type = parts[2];
int bedrooms = Integer.parseInt(parts[3]);
int year = Integer.parseInt(parts[4]);
int rental = Integer.parseInt(parts[5]);
Landlord landlord = theLandlord;
Tenant tenant = null;
org.propUniqueCheck(id);
propNoCheck(propNo, postcode);
postcodeCheck(postcode,propNo);
typeCheck(postcode, propNo, type);
bedroomsCheck(bedrooms, postcode, propNo);
yearCheck(propNo, postcode, year);
System.out.println("Creating property " + id);

Property newProp = new Property(id, propNo, postcode, type, bedrooms, year,
rental, landlord, tenant);
org.newProp(newProp);
org.printProps();
}

/*From here down it is the code to save the value to the array*/

public Organize() {
props = new ArrayList<Property>();
PTs = new ArrayList<PotentialTenant>();
waitingList = new LinkedList<String>();
//myList.add(new prop(Property.toString()));

}
public void newProp(Property p)
{
props.add(p);
}

我一直在研讨会上积极寻求有关此问题的帮助,但我似乎找不到解决方案,非常感谢任何建议!

最佳答案

在 processProperty 中,您正在实例化一个新的 Organize 对象。因此,每个属性(为每行创建的)最终都会出现在不同的 ArrayList 中(作为第一个元素)。

一种解决方案是在开始循环之前实例化一个 Organize 对象,然后将其作为参数传递到 processProperty 方法中。

关于java - 代码仅将文本文件的一行保存到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13723940/

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