我如何在ArrayList
中动态命名对象。所以我有这个:
optionNum = input.nextInt();
switch (optionNum) {
case 1: //Customer Information Retrieval
int i = 0;
System.out.println("What is the customer ID");
customerId = input.next();
newCustomer.setcustomerId(customerId);
System.out.println("What is the customer first name?");
firstName = input.next();
newCustomer.setfirstName(firstName);
System.out.println("What is the customer last name?");
lastName = input.next();
newCustomer.setlastName(lastName);
System.out.println("What is the customer age?");
age = input.nextInt();
newCustomer.setAge(age);
System.out.println("What is the customer income?");
income = input.nextDouble();
newCustomer.setIncome(income);
System.out.println("What is the customer credit score?");
creditScore= input.nextInt();
newCustomer.setcreditScore(creditScore);
newCustomer.Attributes(customerId, firstName, lastName, age, income, creditScore);
customers.add(i, newCustomer);
i++;
break;
它是在while循环中,但每次我添加一个新客户时它会覆盖旧客户,留下两个拥有相同信息的客户。如何让它在循环的每次迭代中创建一个新对象?
答案 0 :(得分:0)
在case块内创建newCustomer对象,而不是在outside。您基本上覆盖了同一个对象,导致先前的值被覆盖,而每次在列表中也会生成一个新条目。
答案 1 :(得分:0)
1)在循环之前声明客户: 客户newCustomer = null; 2)在循环内创建客户实例并在newCustomer对象中设置。 newCustomer = new Customer(); 3)填写客户对象 4)将其添加到客户列表
希望这可以帮助你!!!