1

我生成的代码旨在提供逐行读取文本文件的功能,将每一行保存到一个数组中。它似乎正确地读取了每一行但是当我使用 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);
    }

我一直在我的研讨会上积极寻求解决这个问题的帮助,但我似乎找不到解决方案,任何建议将不胜感激!

4

2 回答 2

1

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

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

于 2012-12-05T13:15:01.923 回答
0

当文本文件中的一行是空字符串时,您的 while 循环将中断。

这是实现循环的正确方法:

String line = "";
while ((line = reader.readLine()) != null) {
    // your code here
}
于 2012-12-05T13:15:03.597 回答