我被困在作業問題......到目前爲止,僅使用數組我遇到了麻煩,通過將它設置爲空對象來刪除數組中的對象。 。我有3種方法,一種方法來添加一個對象,一種方法從數組返回一個特定的對象,一種方法來刪除..到目前爲止,添加和返回對象的方法工作..但不是刪除方法...一些幫助傢伙?需要幫助從普通的對象數組中刪除指定的對象
這是對陣列和方法的類...我測試的方法主要方法
public class Book {
public void addContact(Contact[] contactBook)
{
int slots = 0;
for(Contact i : contactBook)
if (i == null)
slots++;
if(slots == 0)
System.out.println("Contact book full..can't add anymore!");
else
{
String name = Keyboard.readString("Enter name: ");
int id = Keyboard.readInt("Enter "+name+"'s id: ");
String classroom = Keyboard.readString("Enter "+name+"'s class: ");
int number = Keyboard.readInt("Enter "+name+"'s mobile: ");
for (int i = 0; i < contactBook.length; i++)
{
if(contactBook[i] == null){
contactBook[i] = new Contact(name,id,number,classroom);
break;
}
}
}//end else
}//end method
public Contact getContact(Contact[] contactList)
{
Contact contact = null;
int id = Keyboard.readInt("Enter student id: ");
try
{
for(Contact i : contactList)
{
if(i.id == id)
{
contact =i;
break;
}
}
}
catch(NullPointerException e)
{
System.out.println("Student ID:"+id+" does not exist..");
}
return contact;
}//end getContact
public void deleteContact(Contact[] contactList)
{
Contact delete = getContact(contactList);
for(Contact i : contactList)
{
if(i!=null)
if(delete.id == i.id)
{
i = null;
break;
}
}
}//end delete
public static void main(String args[])
{
Contact[] contacts = new Contact[200];
Book newBook = new Book();
newBook.addContact(contacts);
for (Contact i : contacts)
if(i != null)
System.out.println(i);
newBook.deleteContact(contacts);
for (Contact i : contacts)
if(i != null)
System.out.println(i);
}
}
這是該對象的類別 公共類聯繫{
String name;
String classroom;
int id;
int number;
Contact(String name, int id, int number,String classroom)
{
this.name = name;
this.id = id;
this.number = number;
this.classroom = classroom;
}
public String toString()
{
return ""+name+", student id: "+id+" class:"+classroom+" mobile:"+number;
}
}
的
使用ArrayList代替。它會給你更多的命令來操縱你的對象數組。您可以輕鬆地從ArrayList中刪除一個對象。 – 2011-06-15 16:48:24
以及我不允許使用ArrayList .. :( – Shizumaru18 2011-06-15 16:48:53
這真的很糟糕。那麼你可以採取從文件中刪除內容的方式。手段,創建另一個大小的數組-1。你想刪除到新陣列的對象 – 2011-06-15 16:57:20