2

The error is that the customers has different ID, but in readCustomer object of ArrayList class the only ID that is saved is the ID of the last customer.

//reads customer data from register.txt file
//has 2 string as arguments
//returns a ArrayList object with all the customer with the same name

public ArrayList<Customer> readCustomer(String name,String surname){

    Customer temp = new Customer();

    //will hold all the customers with the same name and surname
    ArrayList<Customer> readCustomer = new ArrayList<Customer>();        

    try{
        FileInputStream fstream = new FileInputStream("register.txt");
        BufferedReader fbr = new BufferedReader(new InputStreamReader(fstream));
        String strLine;
        while ((strLine = fbr.readLine()) != null)   {

            String line[];
            line = strLine.split(" ");                
            if(name.equals(line[1]) && surname.equals(line[2])){

                temp.setCustomerID(Integer.parseInt(line[0]));
                temp.setName(line[1]);
                temp.setSurname(line[2]);
                temp.setAddress(line[3]);
                temp.setAge(Integer.parseInt(line[4]));                    
                readCustomer.add(temp);                   

            }
        }
        fbr.close();
    }
    catch(Exception ex){*emphasized text*
        System.out.println(ex.getMessage());            
    }    

    return readCustomer;        
}

3 Answers 3

5

Create a new object on every iteration and not one which gets filled recuringly. Also, learn to understand object references.

while ((strLine = fbr.readLine()) != null)   {
    Customer temp = new Customer();

    // and so on
Sign up to request clarification or add additional context in comments.

Comments

1

Use

Customer temp;//instead of doing Customer temp = new Customer();

And inside iteration do

temp = new Customer();

In every loop a new temp instance is created and thus you can add new customers to the array list as needed for your case.

Comments

0

You are creating the Consumer object only once all the way at the top. That means, every time you are just updating the same object with different values, and adding it to the list. So, you need to create the Consumer object for each and every record that you read from the text file. (i.e) You need to put the following line with in the while loop,

Customer temp = new Customer();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.