我需要幫助。如何將信息添加到ArrayList中已有的對象?
我有一個ArrayList完整的客戶端/客戶名稱。我想要做的是編寫一個代碼,以便它詢問我的客戶名稱,然後輸入它,如果它發現它將一個電話號碼添加到客戶端。一旦添加,如果我想打印列表,電話號碼將在該特定客戶端旁邊。
我有3個班。 1是客戶端類(具有變量 - 名稱,地址,數字)和一個JobManager(整個測試程序使用諸如添加客戶端和刪除一個的方法)。
這是我如何將客戶的樣子:
public static void addClient() {
System.out.println("Adding a client: \n");
System.out.print("What is the name of the new client?: ");
String name = keyboard.nextLine();
System.out.println();
if (name.length() == 0) {
boolean invalid = true;
while (invalid) {
System.out.println("You cannot enter a blank name for the client. ");
System.out.print("Please enter a valid name: ");
name = keyboard.nextLine();
if (name.length() > 0) {
invalid = false;
}
}
}
System.out.print("What is the client's address?: ");
String address = keyboard.nextLine();
boolean isDuplicate = false;
for (int i = 0; i < clientList.size(); i++) {
String listName = clientList.get(i).getName();
String listAddress = clientList.get(i).getAddress();
if (listName.equalsIgnoreCase(name)
&& listAddress.equalsIgnoreCase(address)) {
isDuplicate = true;
if (listName.equalsIgnoreCase(name)) {
isDuplicate = true;
}
}
if (isDuplicate) {
System.out.println();
System.out.println("Error, that client already exists! \n");
isDuplicate = false;
} else {
Client client = new Client(name, address);
clientList.add(client);
System.out.println();
System.out.println("Client has been added. \n");
}
}
}
而這正是我的客戶端類的樣子:
public class Client {
private ArrayList<JobManager> jobManager;
private ArrayList<TelephoneNumber> telephoneNumbers = new ArrayList<>();
private String name;
private String address;
private static int number;
public Client(String name,String address) {
this.name = name;
this.address = address;
}
// public void createNumber() {
// TelephoneNumber teleNumber = new TelephoneNumber(number);
// telephoneNumbers.add(teleNumber);
//}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public static int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String toString() {
String result;
result = name + "\n" + address;
result = (this.getName() + "\t" + this.getAddress());
return result;
}
}
在此先感謝您的答案傢伙!
你的問題是什麼? – Babel
我只是不知道如何將電話號碼添加到列表中存在的特定客戶端。 – Kanox
你有'Client'中的電話號碼列表,但沒有方法添加一個。你不認爲增加一種方法來將電話號碼添加到「客戶端」實例會有幫助嗎? – Tom