I am stuck in my homework ... so far, using only arrays, I have been unable to delete the object in the array by setting it to a null object. I had 3 methods, one method was to add an object, one method to return a specific object from an array, one method to delete ... so the methods of adding and returning objects work ... but not the delete method ... do some help the guys? ?
this is a class for arrays and methods ... I am testing methods in the main method
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+" id: ");
String classroom = Keyboard.readString("Enter "+name+" class: ");
int number = Keyboard.readInt("Enter "+name+" mobile: ");
for (int i = 0; i < contactBook.length; i++)
{
if(contactBook[i] == null){
contactBook[i] = new Contact(name,id,number,classroom);
break;
}
}
}
}
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;
}
public void deleteContact(Contact[] contactList)
{
Contact delete = getContact(contactList);
for(Contact i : contactList)
{
if(i!=null)
if(delete.id == i.id)
{
i = null;
break;
}
}
}
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);
}
}
this is an object class public class Contact {
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;
}
}
source
share