10 Replies - 492 Views - Last Post: 27 April 2013 - 10:42 AM Rate Topic: -----

#1 coilygeekintraining  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 28-March 13

Removing object from ArrayList!

Posted 26 April 2013 - 10:15 AM

I am sure I am not doing something so simple but I can't seem to figure out how to delete the right object.
When I run the code, it keeps deleting the first object in the arraylist instead of the object that is being matched.
I see that when I check (using indexOf), this is probably due to the fact that the index is 0.
Can someone please assist me with deleting the contact that is being matched.
If run the code the issue is with the search and delete. Finds the search correctly but will delete first object in arraylist instead of matched.
Thanks in advance for help!




import java.util.ArrayList;
import java.util.Scanner;

public class ContactDatabase
{
	private ArrayList<Contact> contacts;        // ArrayList for contacts
	
	// Choices for main menu
	private static final int ADD = 1;
	private static final int VIEWALL = 2;
	private static final int SEARCH = 3;
	private static final int DELETE = 4;
	private static final int QUIT = 5; 
	boolean found = false;


 	//Main constructor
	//creates a new ArrayList object with parameter type Contact

	ContactDatabase()
	{
	    contacts = new ArrayList<Contact>();
	}
	
	
	//method to add contacts and store in Arraylist
	
	public void addContact()
	{
	    Contact newContact;
	    String first = "null";
	    String last = "null";
	    String phone = "null";
	    String email = "null";
	    Scanner input = new Scanner(System.in);
		 
		 while (true)
    	 {
		 		//get first name
				//first name cannot be blank
	       	System.out.println("Please enter first name of new person");
	        	first = input.nextLine();
	        	if (first.equals(""))
	        	{
	            System.out.println("First name cannot be blank!");
	         }
	         
				else
	         {
	         break;
	         }
		 }
		 
		 //get last name
		 //last name cannot be blank
		 
		 while (true)
    	 {
	        System.out.println("Please enter last name of new person");
	        last = input.nextLine();
	        if (last.equals(""))
	        {
	            System.out.println("Last name cannot be blank!");
	        }
	        else
	        {
	        break;
	        }
       }

		 while (true)
    	 {
	        System.out.println("Please enter a phone number for " + first);
			  System.out.println("Please use the following format: xxx-xxx-xxxx");
	        phone = input.nextLine();
			  if (phone.equals(""))
	        {
	            System.out.println("Phone number cannot be blank!");
	        }
			  
	        else
	        {
					phone = phone.replaceAll("\\-","");
					phone = phone.replaceAll("\\(","");
					phone = phone.replaceAll("\\)","");
		         break;
			  }
    	 }
		
		
		 while (true)
    	 {
	        System.out.println("Please enter an e-mail for " + first + ": ");
			  System.out.println("Please use the following format xxx@xxx.com");
			  System.out.println();
	        email = input.nextLine();
			  
			  if (email.equals(""))
	        {
	            System.out.println("Email cannot be blank!");
					System.out.println();
	        }
			  
	        else if (email.indexOf('@') < 0) 
			  {
					System.out.println("No '@' in email address\n Please enter a correct email address: ");
					System.out.println();
			  }
			
			  else if (email.indexOf('.') < 0) 
			  {
					System.out.println("No '.' in email address!");	
					System.out.println();		  
    	     }
			  
			  else
			  {
			  		break;
			  }
		 }


			 newContact = new Contact(first, last, phone, email);
		    contacts.add(newContact);
		
		
			 System.out.println("The following contact has been added successfully:");
		    System.out.println(newContact);
			 System.out.println();
	}
	
	
	
	//displayAll iterates through the ArrayList of contacts and outputs each one

	public void displayAll()
	{
		 if(contacts.isEmpty())
	     {
	         System.out.println("Sorry, there is no contacts in database.");
				System.out.println();
	     }
		 
		 else
		 { 
			    System.out.println("Contacts currently in database:");
				 System.out.println();
			    for (Contact entry : contacts)
			    System.out.println (entry);
		}
	}


	//View match contacts through search 
	//Outputs matches to screen if found
	
	public void viewMatch()
	{
	    //boolean found = false;
	    Scanner input = new Scanner(System.in);
		 
		  if(contacts.isEmpty())
	     {
	         System.out.println("Sorry, there is no contact information to search.");
				System.out.println();
				
	     }
		  
		  else
		  {
			    System.out.print("Please enter contact keyword to search for: ");
			    String search = input.next().trim().toLowerCase();
	   
		        for(Contact a: contacts)
		        {
		            if((a.getFirst().toLowerCase().contains(search))||
							(a.getLast().toLowerCase().contains(search))||
							(a.getPhone().toLowerCase().contains(search))||
							(a.getEmail().toLowerCase().contains(search)))
		            {
		                System.out.println("Here is the contact found: ");
		                System.out.print("Name: " + a.getFirst());
		                System.out.println(" " + a.getLast());
		                System.out.println("Phone number: " + a.getPhone());
		                System.out.println("Email: " + a.getEmail());
							 
		                found = true;
		            }
		        }
	    
			    if (found == false)
			    {
			        System.out.println("Sorry, no such contact");
					  System.out.println();
			    }
		 
		 }
	}
	
	
	//deleteMatch searches for contact and deletes if found.
	//checks if correct contact and if should be deleted

	public void deleteMatch()
	{
	    for(Contact a: contacts)
		 {
			viewMatch();
				
			if(found == true)
			{
				
				 //for (int i=0; i< contacts.size(); i++)
				 //for(Contact a: contacts)

			   // {
			       
			        Scanner delete = new Scanner(System.in);
			        System.out.println("Is this the contact that should be deleted? Yes or No");
			        String answer = delete.next();
			        if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y"))
			        {	
					  		
					  		System.out.println(contacts.indexOf(a)); // checking index
							
			            contacts.remove(contacts.indexOf(a));
			            System.out.println("Contact has been deleted.");
			            displayAll();
			        }
					  
					  else
					  {
					  		System.out.println("Contact has NOT been deleted.");
			            displayAll();
							break;
					  }
			
					  
					  
			    //}
			}
	 	}
	}
	
	
	
	
	// Main class
	public static void main(String[] args)
	{
	    ContactDatabase database = new ContactDatabase();
	    Scanner keyboard = new Scanner(System.in);
	    int choice = ADD;
	
	    // Main menu
	    while (choice != QUIT)
	    {
	        System.out.println();
	        System.out.println("Choose from the following:");
	        System.out.println("1) Add new contact");
	        System.out.println("2) List all contacts");
	        System.out.println("3) Search contacts and display");
	        System.out.println("4) Search contacts and delete");
			  System.out.println("5) Quit");
	        choice = keyboard.nextInt();
	        switch (choice)
	        {
	            case ADD:   database.addContact();
	                        break;
	            case VIEWALL: database.displayAll();
	                        break;
	            case SEARCH: database.viewMatch();
	                        break;
	            case DELETE: database.deleteMatch();
	                        break;
	        }
	    }
	}




}

class Contact
{
   private String first;
	private String last; 
	private String phone;
	private String email;
	
   public Contact()
   {
   }

   public Contact(String first, String last, String phone, String email)
   {
      this.first = first;
      this.last = last;
      this.phone = phone;
      this.email = email;
   }

  
  //accessor methods to get name, phone number and email
   public String getFirst()
   {
      return first;
   }

   public String getLast()
   {
      return last;
   }

   public String getPhone()
   {
      return phone;
   }

   public String getEmail()
   {
      return email;
   }

   
	//Mutator Methods to set name, phone number, and email
   public void setFirst(String first)
   {
      this.first = first;
   }

   public void setLast(String last)
   {
      this.last = last;
   }

   public void setPhone(String phone)
   {
      this.phone = phone;
   }

   public void setEmail(String mail)
   {
      this.email = mail;
   }



   //method to print out information   
   public String toString()
   {
      return "\nName: " + first + " " + last + "\n" + "Phone: " + phone + "\nEmail: " + email + "\n";
   }


   public boolean equals(Object otherObject)
   {
      if (otherObject ==null)
      {
         return false;
      }
      else if (getClass() != otherObject.getClass())
      {
         return false;
      }
      else
      {
         Contact otherContact = (Contact)otherObject;
         return (first.equals(otherContact.first) &&
               last.equals(otherContact.last)&&
               phone.equals(otherContact.phone)&&
               email.equals(otherContact.email));
      }
   }

} 




Is This A Good Question/Topic? 0
  • +

Replies To: Removing object from ArrayList!

#2 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2198
  • View blog
  • Posts: 5,226
  • Joined: 10-September 10

Re: Removing object from ArrayList!

Posted 26 April 2013 - 10:30 AM

I didn't spend a ton of time at it, but I don't understand how deleteMatch() and viewMatch() are connected. Look at that more closely and ensure that viewMatch() is searching for the right item and that once found, the item is being identified correctly to deleteMatch() so the right item is being deleted.

It appears to me that once viewMatch() finds the desired item, deleteMatch() deletes the next item which is always the item at the zero index, because viewMatch() doesn't tell deleteMatch() which item to delete.
Was This Post Helpful? 1
  • +
  • -

#3 coilygeekintraining  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 28-March 13

Re: Removing object from ArrayList!

Posted 26 April 2013 - 10:35 AM

With deleteMatch it's suppose to search for contact, display, and delete.
Because it's suppose to display contact, that is why I put viewMatch within that method instead of re-writing the entire method if that makes sense?
I guess it's not relying which item specifically to deleteMatch though as you are saying.
Was This Post Helpful? 0
  • +
  • -

#4 darek9576  Icon User is offline

  • D.I.C Lover

Reputation: 198
  • View blog
  • Posts: 1,689
  • Joined: 13-March 10

Re: Removing object from ArrayList!

Posted 26 April 2013 - 10:39 AM

About your Contact class. Whenever you override the equals() method, you have to also override the hashCode() method so that objects that are equal will return same hashCode. Default implementation is that it returns an integer representation of the address in memory which is different for every object.

And your equals() method could include another if statement like this:

boolean equals(Object obj){
   if(this == obj) return true;
   //the rest of your stuff
}

Was This Post Helpful? 1
  • +
  • -

#5 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2198
  • View blog
  • Posts: 5,226
  • Joined: 10-September 10

Re: Removing object from ArrayList!

Posted 26 April 2013 - 11:24 AM

I recommend you generalize the collection of data from the user so that you don't have to have multiple clauses that do the same thing except for customized error messages. Instead of coding, "Last Name cannot be blank", "Email cannot be blank", "Phone cannot be blank," and on and on, you could generalize the collection algorithm to obtain the data name from an array so that the warning would be:

System.out.println( dataName[i] + " cannot be blank. Please complete." );

Or you could skip naming the data field entirely, and simply tell the user:

System.out.println( "This field cannot be left blank. Please complete." );
Was This Post Helpful? 1
  • +
  • -

#6 coilygeekintraining  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 28-March 13

Re: Removing object from ArrayList!

Posted 26 April 2013 - 11:47 AM

View PostGregBrannon, on 26 April 2013 - 11:24 AM, said:

I recommend you generalize the collection of data from the user so that you don't have to have multiple clauses that do the same thing except for customized error messages. Instead of coding, "Last Name cannot be blank", "Email cannot be blank", "Phone cannot be blank," and on and on, you could generalize the collection algorithm to obtain the data name from an array so that the warning would be:

System.out.println( dataName[i] + " cannot be blank. Please complete." );

Or you could skip naming the data field entirely, and simply tell the user:

System.out.println( "This field cannot be left blank. Please complete." );


Okay will do! thanks.

The right match is being deleted but now I'm getting this error after contact is deleted.

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at ContactDatabase3.deleteMatch(ContactDatabase3.java:225)
at ContactDatabase3.main(ContactDatabase3.java:310)



Can anyone help on how I would fix this?



//
//
//
//

import java.util.ArrayList;
import java.util.Scanner;

public class ContactDatabase3
{
	private ArrayList<Contact> contacts;        // ArrayList for contacts
	
	// Choices for main menu
	private static final int ADD = 1;
	private static final int VIEWALL = 2;
	private static final int SEARCH = 3;
	private static final int DELETE = 4;
	private static final int QUIT = 5; 
	boolean found = false;


 	//Main constructor
	//creates a new ArrayList object with parameter type Contact

	ContactDatabase3()
	{
	    contacts = new ArrayList<Contact>();
	}
	
	
	//method to add contacts and store in Arraylist
	
	public void addContact()
	{
	    Contact newContact;
	    String first = "null";
	    String last = "null";
	    String phone = "null";
	    String email = "null";
	    Scanner input = new Scanner(System.in);
		 
		 while (true)
    	 {
		 		//get first name
				//first name cannot be blank
	       	System.out.println("Please enter first name of new person");
	        	first = input.nextLine();
	        	if (first.equals(""))
	        	{
	            System.out.println("First name cannot be blank!");
	         }
	         
				else
	         {
	         break;
	         }
		 }
		 
		 //get last name
		 //last name cannot be blank
		 
		 while (true)
    	 {
	        System.out.println("Please enter last name of new person");
	        last = input.nextLine();
	        if (last.equals(""))
	        {
	            System.out.println("Last name cannot be blank!");
	        }
	        else
	        {
	        break;
	        }
       }

		 while (true)
    	 {
	        System.out.println("Please enter a phone number for " + first);
			  System.out.println("Please use the following format: xxx-xxx-xxxx");
	        phone = input.nextLine();
			  if (phone.equals(""))
	        {
	            System.out.println("Phone number cannot be blank!");
	        }
			  
	        else
	        {
					phone = phone.replaceAll("\\-","");
					phone = phone.replaceAll("\\(","");
					phone = phone.replaceAll("\\)","");
		         break;
			  }
    	 }
		
		
		 while (true)
    	 {
	        System.out.println("Please enter an e-mail for " + first + ": ");
			  System.out.println("Please use the following format xxx@xxx.com");
			  System.out.println();
	        email = input.nextLine();
			  
			  if (email.equals(""))
	        {
	            System.out.println("Email cannot be blank!");
					System.out.println();
	        }
			  
	        else if (email.indexOf('@') < 0) 
			  {
					System.out.println("No '@' in email address\n Please enter a correct email address: ");
					System.out.println();
			  }
			
			  else if (email.indexOf('.') < 0) 
			  {
					System.out.println("No '.' in email address!");	
					System.out.println();		  
    	     }
			  
			  else
			  {
			  		break;
			  }
		 }


			 newContact = new Contact(first, last, phone, email);
		    contacts.add(newContact);
		
		
			 System.out.println("The following contact has been added successfully:");
		    System.out.println(newContact);
			 System.out.println();
	}
	
	
	
	//displayAll iterates through the ArrayList of contacts and outputs each one

	public void displayAll()
	{
		 if(contacts.isEmpty())
	     {
	         System.out.println("Sorry, there is no contacts in database.");
				System.out.println();
	     }
		 
		 else
		 { 
			    System.out.println("Contacts currently in database:");
				 System.out.println();
			    for (Contact entry : contacts)
			    System.out.println (entry);
		}
	}


	//View match contacts through search 
	//Outputs matches to screen if found
	
	public void viewMatch()
	{
	    //boolean found = false;
	    Scanner input = new Scanner(System.in);
		 
		  if(contacts.isEmpty())
	     {
	         System.out.println("Sorry, there is no contact information to search.");
				System.out.println();
				
	     }
		  
		  else
		  {
			    System.out.print("Please enter contact keyword to search for: ");
			    String search = input.next().trim().toLowerCase();
	   
		        for(Contact a: contacts)
		        {
		            if((a.getFirst().toLowerCase().contains(search))||
							(a.getLast().toLowerCase().contains(search))||
							(a.getPhone().toLowerCase().contains(search))||
							(a.getEmail().toLowerCase().contains(search)))
		            {
		                System.out.println("Here is the contact found: ");
		                System.out.print("Name: " + a.getFirst());
		                System.out.println(" " + a.getLast());
		                System.out.println("Phone number: " + a.getPhone());
		                System.out.println("Email: " + a.getEmail());
							 
		                found = true;
		            }
		        }
	    
			    if (found == false)
			    {
			        System.out.println("Sorry, no such contact");
					  System.out.println();
			    }
		 
		 }
	}
	
	
	//deleteMatch searches for contact and deletes if found.
	//checks if correct contact and if should be deleted

	public void deleteMatch()
	{
	    Scanner input = new Scanner(System.in);
		 
		  if(contacts.isEmpty())
	     {
	         System.out.println("Sorry, there is no contact information to search.");
				System.out.println();
				
	     }
		  
		  else
		  {
			    System.out.print("Please enter contact keyword to search for: ");
			    String search = input.next().trim().toLowerCase();
	   
		        for(Contact a: contacts)
		        {
		            if((a.getFirst().toLowerCase().contains(search))||
							(a.getLast().toLowerCase().contains(search))||
							(a.getPhone().toLowerCase().contains(search))||
							(a.getEmail().toLowerCase().contains(search)))
		            {
		                System.out.println("Here is the contact found: ");
		                System.out.print("Name: " + a.getFirst());
		                System.out.println(" " + a.getLast());
		                System.out.println("Phone number: " + a.getPhone());
		                System.out.println("Email: " + a.getEmail());
							 
		                found = true;
		            
						
							Scanner delete = new Scanner(System.in);
							System.out.println("Is this the contact that should be deleted? Yes or No");
						   String answer = delete.next();
										  
								        if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y"))
								        {	
										  		
										  		System.out.println(contacts.indexOf(a));
												contacts.remove(contacts.indexOf(a));
								            System.out.println("Contact has been deleted.");
								            //displayAll();
												
								        }
										  
										  else
										  {
										  		System.out.println("Contact has NOT been deleted.");
								            displayAll();
												
										  }
			
					  
					  
			   
						}
						
		        }
				  
				 if (found == false)
			    {
			        System.out.println("Sorry, no such contact");
					  System.out.println();
			    }

	    
			   
				 
				 
		 
		 }
	}
	
	
	
	
	// Main class
	public static void main(String[] args)
	{
	    ContactDatabase3 database = new ContactDatabase3();
	    Scanner keyboard = new Scanner(System.in);
	    int choice = ADD;
	
	    // Main menu
	    while (choice != QUIT)
	    {
	        System.out.println();
	        System.out.println("Choose from the following:");
	        System.out.println("1) Add new contact");
	        System.out.println("2) List all contacts");
	        System.out.println("3) Search contacts and display");
	        System.out.println("4) Search contacts and delete");
			  System.out.println("5) Quit");
	        choice = keyboard.nextInt();
	        switch (choice)
	        {
	            case ADD:   database.addContact();
	                        break;
	            case VIEWALL: database.displayAll();
	                        break;
	            case SEARCH: database.viewMatch();
	                        break;
	            case DELETE: database.deleteMatch();
	                        break;
	        }
	    }
	}




}


class Contact
{
   private String first;
	private String last; 
	private String phone;
	private String email;
	
   public Contact()
   {
   }

   public Contact(String first, String last, String phone, String email)
   {
      this.first = first;
      this.last = last;
      this.phone = phone;
      this.email = email;
   }

  
  //accessor methods to get name, phone number and email
   public String getFirst()
   {
      return first;
   }

   public String getLast()
   {
      return last;
   }

   public String getPhone()
   {
      return phone;
   }

   public String getEmail()
   {
      return email;
   }

   
	//Mutator Methods to set name, phone number, and email
   public void setFirst(String first)
   {
      this.first = first;
   }

   public void setLast(String last)
   {
      this.last = last;
   }

   public void setPhone(String phone)
   {
      this.phone = phone;
   }

   public void setEmail(String mail)
   {
      this.email = mail;
   }



   //method to print out information   
   public String toString()
   {
      return "\nName: " + first + " " + last + "\n" + "Phone: " + phone + "\nEmail: " + email + "\n";
   }


   public boolean equals(Object otherObject)
   {
	   if(this == otherObject) 
		{
			return true;
	   }
	
		else if (otherObject ==null)
      {
         return false;
      }
      else if (getClass() != otherObject.getClass())
      {
         return false;
      }
      else
      {
         Contact otherContact = (Contact)otherObject;
         return (first.equals(otherContact.first) &&
               last.equals(otherContact.last)&&
               phone.equals(otherContact.phone)&&
               email.equals(otherContact.email));
      }
   }

} 



Was This Post Helpful? 0
  • +
  • -

#7 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 7748
  • View blog
  • Posts: 13,106
  • Joined: 19-March 11

Re: Removing object from ArrayList!

Posted 26 April 2013 - 11:51 AM

I'd start, as always, by reading about what a ConcurrentModificationException is:

http://docs.oracle.c...nException.html


This should at least point you in the right direction.
Was This Post Helpful? 1
  • +
  • -

#8 coilygeekintraining  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 28-March 13

Re: Removing object from ArrayList!

Posted 26 April 2013 - 12:02 PM

I have read what it is, just not understanding really how to incorporator an iterator in which is what is suggested instead of a for each loop.

incorporate*
Was This Post Helpful? 0
  • +
  • -

#9 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2198
  • View blog
  • Posts: 5,226
  • Joined: 10-September 10

Re: Removing object from ArrayList!

Posted 26 April 2013 - 01:18 PM

We don't get to see this one too often.

It would be helpful if you'd show us how to duplicate the error. Copy and paste the terminal session between code tags that resulted in the error message. Don't use data in the example that you don't want everyone to know. DIC rules prohibit displaying real email addresses and phone numbers, but you shouldn't ever do that anyway.

This post has been edited by GregBrannon: 26 April 2013 - 01:24 PM

Was This Post Helpful? 0
  • +
  • -

#10 coilygeekintraining  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 28-March 13

Re: Removing object from ArrayList!

Posted 26 April 2013 - 01:21 PM

Thanks everyone!
Figured out how to fix the error
by using a second array list.

Thanks so much for all your input!
Was This Post Helpful? 0
  • +
  • -

#11 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8332
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Removing object from ArrayList!

Posted 27 April 2013 - 10:42 AM

Never a good idea to use an iterator if you plan to modify the Collection

   for(Contact a: contacts)

use:

   // start by the end so i will still point to the good one if you remove at i
   for(int i = contacts.size(); --i >= 0;) {
         Contact a = contacts.get(i);
         if(condition)
            contacts.remove(i);


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1