我奇怪地遇到了一個為我的聯系人類打印 null 的問題。它似乎不喜歡 PhoneNumberList 的數字構造函數。我只是想返回跟蹤數字等的計數,但它只為 getNumber 和 getNumberCount 返回 null。嘗試將計數從私有更改為公共以直接訪問以及更改名稱和構造函數。 public class Contact{ private String name; private PhoneNumberList numbers; // Purpose: // initialize this instance of Contact // with no PhoneNumber // public Contact (String theName) { // You must allocate a PhoneNumberList here numbers = new PhoneNumberList(); name = theName; } // Purpose: // initialize this instance of Contact // add p to the list of phone numbers associated with // this Contact // public Contact (String theName, PhoneNumber p) { // You must allocate a PhoneNumberList here PhoneNumberList numbers = new PhoneNumberList(); name = theName; numbers.add(p); } // Purpose: // return the name associated with this instance // public String getName () { return name; } // Purpose: // change the name associated with this instance to be newName // public void setName(String newName) { name = newName; } // Purpose: // add a new PhoneNumber to this contact // there is no maximum number of phone numbers that can be // assigned to a contact. // public void addNumber (PhoneNumber p) { numbers.add(p); } // Purpose: // remove p from the list of PhoneNumbers associated with this contact // if p is not in the list, do nothing. // public void removeNumber (PhoneNumber p) { int index = numbers.find(p); numbers.remove(index); } // Purpose: // return the count of PhoneNumbers associated with this contact // public int getNumberCount() { return numbers.count; }
1 回答

紅糖糍粑
TA貢獻1815條經驗 獲得超6個贊
以下構造函數是錯誤的。它正在方法中創建一個名稱為 numbers 的臨時對象。
public Contact (String theName, PhoneNumber p)
{
// You must allocate a PhoneNumberList here
PhoneNumberList numbers = new PhoneNumberList();
name = theName;
numbers.add(p);
}
您需要將其更改為
public Contact (String theName, PhoneNumber p)
{
// You must allocate a PhoneNumberList here
numbers = new PhoneNumberList();
name = theName;
numbers.add(p);
}
添加回答
舉報
0/150
提交
取消