gpt4 book ai didi

java - ArrayList方法添加错误

转载 作者:行者123 更新时间:2023-11-30 06:16:58 25 4
gpt4 key购买 nike

错误是客户有不同的 ID,但在 ArrayList 类的 readCustomer 对象中,唯一保存的 ID 是最后一个客户的 ID。

//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;
}

最佳答案

在每次迭代时创建一个新对象,而不是重复填充的对象。此外,学习理解对象引用。

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

// and so on

关于java - ArrayList方法添加错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26451585/

25 4 0