2015-03-31 40 views
0

無法弄清楚爲什麼此代碼不會阻止重複客戶端,重複項是具有相同名稱的客戶端。阻止arraylist中的重複項

我知道這個問題有更好的解決方案。但我只是一個初學者,想用下面的方式來解決這個問題。感謝您的幫助......

import java.util.*; 

public class Kund { 


public static ArrayList<Kund> customerList = new ArrayList<>(); 


public static void addCustomer(){ 

System.out.println("Add a customer:"); 

String customerXName = Program.readString("Name of Customer: "); 
String customerXAdress = Program.readString("Adress of Customer: "); 

for (int index = 0; index < customerList.size(); index++) { 
    Customer customerobj = customerList.get(index); 

    if (customerobj.getName().equalsIgnoreCase(customerXName)) { 
     System.out.println("Customer with the given name already exists.  Choose another name..."); 
     addCustomer(); 
     break; 
    } 
} 

Customer customerX = new Customer(customerXName, customerXAdress); 

customerList.add(customerX); 

System.out.println("The following customer has been registered: " 
     + customerX); 
System.out.println(customerList); 
System.out.println(); 

}

+3

break只是打破了for循環。嘗試「返回」而不是「休息」,否則程序會繼續執行for-loop並插入帶有重複名稱的客戶。 – fiffy 2015-03-31 11:27:38

回答

0

您正在使用遞歸,這就是問題所在。一旦你找到一個名字出現在列表中,你再次調用addCustomer()方法。在其中一個調用中,用戶輸入的名稱不在列表中,將其添加到列表中,然後從方法返回。

從上次調用返回後,控件將到達前一個方法調用的堆棧,從循環繼續到break,並且在循環外部,它向客戶添加當前堆棧的名稱和地址,即重複的,但仍然被添加。

呼叫跟蹤是這樣的:

addCustomer() // name = "A", found duplicate 
    addCustomer() // name = "B", found duplicate 
     addCustomer() // name = "C", no duplicate. 
     // add the customer with name = "C" 
     // return to the previous call 
    break the loop 
    // outside the loop, add customer with name = "B" to the list 
    // return to the previous call 
break the loop 
// outside the loop, add customer with name = "A" to the list 

爲了解決這個問題,你可以從return方法,而不是使用break,或更好的使用循環來代替。

+0

還沒有使用do-while循環,所以我必須先閱讀一些關於它的內容。但是,當我使用回報;而不是休息;它實際上工作。 – JLS 2015-03-31 11:39:06

+0

你有沒有一個例子,我可以使用循環而不是返回? – JLS 2015-03-31 11:42:19

1

如果輸入的是已經存在於列表中的客戶,循環會發現它,並要求你輸入一個新的客戶。但是,輸入新客戶後,您不會重新啓動循環,因此您不會檢查輸入的新客戶是否不在列表中。

此外,每次發現客戶已經存在時,遞歸調用addCustomer並不是一個好主意,因爲一旦循環結束,客戶就會被添加。

+0

不重啓循環是什麼意思?當然,對於每個方法調用,您都會重新讀取用戶輸入,並且會有新的'for'循環。 – 2015-03-31 11:32:56