它應該保持Contact_List按姓氏的字母順序。我一直在這裏待了好幾個小時,卻無法弄清楚。我在帖子中添加了add方法和findContactIndex方法,該方法應該可以找到聯繫人的索引。我不斷收到空指針異常和其他錯誤。我需要做的就是找出它按字母順序排列的位置,然後將新的聯繫人插入並將其移回,以便它們都按正確的順序排列。請幫助修復我的添加方法
public void add(Contact frnd)
{
if(numContacts == 0)
{
Contact_List[0] = frnd;
}
else
{
for(int i = 0; i < numContacts; i++)
{
int x =Contact_List[i].getLastName().compareToIgnoreCase(frnd.getLastName());
if(x < 0)
{
Contact_List[findContactIndex(Contact_List[i].getLastName())] = frnd;
break;
}
}
}
numContacts++;
}
/**
* Searches the Contact_List to find a contact by last name
* @param lstnm The last name of a Contact to be found
* @return indexOfContact The index of the contact that has been found
*/
public int findContactIndex(String lstnm)
{
int indexOfContact = -1; // Defaults it at 0 incase the name is not found
for(int i = 0; i < numContacts; i++) // Once for every Contact
{
int a = lstnm.compareTo(Contact_List[i].getLastName());
if(a == 0) // If the Contact is found
{
indexOfContact = i; // Assign the index of that Contact
}
}
return indexOfContact;
}
你在哪裏初始化你的數組?也許你應該使用一個集合? – 2013-04-05 06:31:34
我必須使用一個數組,並且它在類的前面初始化 – 2013-04-05 06:32:48
那麼尺寸管理呢? - 是否給出了聯繫人總數的大小?不幸的是,Java對數組有點痛苦...... – 2013-04-05 06:37:56