無法弄清楚爲什麼此代碼不會阻止重複客戶端,重複項是具有相同名稱的客戶端。阻止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();
}
break只是打破了for循環。嘗試「返回」而不是「休息」,否則程序會繼續執行for-loop並插入帶有重複名稱的客戶。 – fiffy 2015-03-31 11:27:38