Jump to content

Java array phonebook problem

SeigiroSpica
Go to solution Solved by Franck,

You can always change this code to another format that might make it more sense to you this way. Technically it's does the same thing but you might understand it better that way. There is one small difference and that it is bulletproof for the comparaison like this (except possible error handling in the future).

 

Your current code if you delete a contact in the middle of the list you will never check the other contact after that deleted contact as you will find a null contact and get out immediately.

 

This version will check all contacts and will get out under 2 conditions, If it finds the contact in the array or if it iterated the whole array and found nothing.

 

 public boolean existeContacto(Contacto c)
 {
    bool contactFound = false;
   
    for (int i = 0; i < persona.length; i++)
    {
        // if the contact at the index is not null check if it's the same
        if (persona[i] != null && persona[i].getNombre().equals(c.getNombre()))
        {
            // if it's the same mark as found
            contactFound = true;
          
            // break out the loop so it return immediately without bothering checking for the other contacts
            break;
        }
    }
   
    return contactFound;
}

 

Okay, i'm trying to do a phonebook
I have the main (AdC), the class of the phonebook (Agenda) where all the methods are in, and a class for the contacts (Contacto) with their phone number and name.
What i'm trying to do in the main is to add a new contact with the option 1 using the method addContacto(Contacto c).

I can add the first contact with no problem. I can show it with the option 5 that use the method listarContacto().

But when I try to add a second contact with the class addContacto(Contacto c) for some reason when is checking if the "new" contact already exist with the method existeContacto(Contacto C) even tho I type a different name and phone number it responds that the contact exist and that I can't add a new contact. And at the same time replaces the first contact that I added with the second one, even tho it told it shouldn't since responded that I can't add in the condition "If" of existeContacto().

 

I don't know what the problem is and is taking me hours already...

I can't see it or I don't understand something basic....

 

Agenda main.jpg

Contacto class.jpg

Agenda class.jpg

Link to comment
Share on other sites

Link to post
Share on other sites

image.png.4a19de9ed88b7f323f270376313cacab.png

 

You haven't overridden the equals method for your class so its behavior is probably not what you think it is. You can either fix the existeContacto method to actually do the comparison you want or override the equals method in your class to do it. For the former:

public boolean existeContacto(Contacto c){
    for(int i = 0; i < persona.length; i++){
        if(c.getNombre().equals(persona[i].getNombre())) return true;
    }
    return false;
}

 

Don't ask to ask, just ask... please 🤨

sudo chmod -R 000 /*

Link to comment
Share on other sites

Link to post
Share on other sites

42 minutes ago, Sauron said:

image.png.4a19de9ed88b7f323f270376313cacab.png

 

You haven't overridden the equals method for your class so its behavior is probably not what you think it is. You can either fix the existeContacto method to actually do the comparison you want or override the equals method in your class to do it. For the former:


public boolean existeContacto(Contacto c){
    for(int i = 0; i < persona.length; i++){
        if(c.getNombre().equals(persona[i].getNombre())) return true;
    }
    return false;
}

 

That is not enough to correct the code but he needs it.

 

To the OP, check your contact object

image.png.d6350430e8d3ca70c469bd8eb4c85288.png

 

it is created only once, it has a specific location in memory for that object.

When you add it to the list it will have a reference (pointer) to that variable and it does not contain the actual object.

You need to bring the Contacto contacto = new Contacto(); into the switch case 1.

 

This will create a new object each time and the Agenda will contain different object each time. If you don't do that and add many

contact with the same reference object when you change a value like the name all of them change to the same thing since they are the same object.

 

Link to comment
Share on other sites

Link to post
Share on other sites

18 minutes ago, Franck said:

That is not enough to correct the code but he needs it.

 

To the OP, check your contact object

image.png.d6350430e8d3ca70c469bd8eb4c85288.png

 

it is created only once, it has a specific location in memory for that object.

When you add it to the list it will have a reference (pointer) to that variable and it does not contain the actual object.

You need to bring the Contacto contacto = new Contacto(); into the switch case 1.

 

This will create a new object each time and the Agenda will contain different object each time. If you don't do that and add many

contact with the same reference object when you change a value like the name all of them change to the same thing since they are the same object.

 

Nice catch, I didn't notice that

Don't ask to ask, just ask... please 🤨

sudo chmod -R 000 /*

Link to comment
Share on other sites

Link to post
Share on other sites

@Franck @Sauron thank you very much both.
I did what you recommended me, I did first what Franck

I got the code to work puttin the creation of Contacto inside the case 1 everthing work fine then I went to test if I get the error "This contact already exist" from ExisteContacto(Contacto) I didn't get that message, so I then proceedd to try and fix the error that Sauron explained going from:
    if (c.equals(persona[i]) ) { return true; }

//(This was always true since C was a new contacto in the main every time the user tries to add a new contact as i understand it)
 
to:

    if (c.getNombre().equals(persona[i].getNombre())) {return true;}
I wanted to get the names to compare but this just break the code the moment it hits the "If", i think it has to do with something in the array persona when it tries to grab the name that it set as null. Or maybe the whole persona is the problem since it's null, but with the equals doesn't seem to have a problem with that...
 
I think I still don't understand objects or arrays very well, because I can't see what the problem is...
Link to comment
Share on other sites

Link to post
Share on other sites

 
6 minutes ago, SeigiroSpica said:

Or maybe the whole persona is the problem since it's null, but with the equals doesn't seem to have a problem with that...

 
I think I still don't understand objects or arrays very well, because I can't see what the problem is...

If the object can be null you should explicitly check for that.

 

if (c != null && c.getNombre().equals(persona[i].getNombre())) {return true;}

Don't ask to ask, just ask... please 🤨

sudo chmod -R 000 /*

Link to comment
Share on other sites

Link to post
Share on other sites

You need to override the Equals in our Contacto class and make the comparing logic for each properties.

 

As for this :

3 minutes ago, SeigiroSpica said:

think I still don't understand objects or arrays very well, because I can't see what the problem is...

An object is what it is, and object, it has properties and can do stuff. It has a meaning.

A pencil is an object, it has a Length property, a Color property, it also has methods/Functions like Sharpen()

 

And array is a list of fix length. Think of it as conveyor belt with bunch of bucket on it.

 

When you create a new pencil "Pencil myPencil = new Pencil()" you just created a new physical object that just pop in reality, for the computer that is 99% of the time the RAM.

id you are to put the pencil in the array (one bucket) it would be problematic to manipulate the array if all the possible millions of pencil would be added there. So instead that array store a pointer. Think of it as a unique number generated when you created that pencil (this happen only ONCE in the lifetime of an object).

 

So you take that unique number, write it on a piece of paper and put that in the bucket. So when you are working with the array you look at the bucket, take the paper and that unique number you know where it is your pencil located or at least which one to look for. This is done automatically for you in Java.

 

Now the problem as i explained for reference is since you were not creating a new "Pencil" object, the unique number stay the same, so each bucket would have a paper in it but all pointing to the same pencil. So if you decide to take bucket #4 and modify the length of the pencil in there, it changes the length of a single pencil forever but all bucket point to that same pencil so no matter which bucket you are looking at they all have the same pencil it in.

Link to comment
Share on other sites

Link to post
Share on other sites

Thank you very much @Sauron and @Franck for the help with my homework, it's still kinda hard for me but I got the code to work, at least to make existeContracto(Contacto c) work, I tried to break it, wasn't able yet, so i think i'm ready to keep going with the rest of the code.

 

At first I did what @Sauron told me buy it kept returning the same error of null pointer
 

So I tried something with all you guys explained to me uptil now, and it worked.

This is the fix that I did, I don't know if it's perfect or the best, but

 

    public boolean existeContacto(Contacto c){
        for (int i=0;i<persona.length;i++){
                if (persona[i]==null){
                return false;
                }
                else {
                    if (persona [i].getNombre().equals(c.getNombre())){
                        return true;
                }
            }
        }
        return false;
    }
    

So the first if checks for the null if it's null, then sends a false to addContacto, so it can add the new contact
if it sends true, checks if the contact has the same name, and if it is it sends the message "You can't add the same contact"
I think the last false is kinda redundant but if I take it out it breaks everything, so...
But for the rest it works fine

Link to comment
Share on other sites

Link to post
Share on other sites

8 minutes ago, SeigiroSpica said:

I think the last false is kinda redundant but if I take it out it breaks everything, so...

It's not redundant, the function must always return a boolean so you need to account for the case where the loop ends without returning anything.

Don't ask to ask, just ask... please 🤨

sudo chmod -R 000 /*

Link to comment
Share on other sites

Link to post
Share on other sites

You can always change this code to another format that might make it more sense to you this way. Technically it's does the same thing but you might understand it better that way. There is one small difference and that it is bulletproof for the comparaison like this (except possible error handling in the future).

 

Your current code if you delete a contact in the middle of the list you will never check the other contact after that deleted contact as you will find a null contact and get out immediately.

 

This version will check all contacts and will get out under 2 conditions, If it finds the contact in the array or if it iterated the whole array and found nothing.

 

 public boolean existeContacto(Contacto c)
 {
    bool contactFound = false;
   
    for (int i = 0; i < persona.length; i++)
    {
        // if the contact at the index is not null check if it's the same
        if (persona[i] != null && persona[i].getNombre().equals(c.getNombre()))
        {
            // if it's the same mark as found
            contactFound = true;
          
            // break out the loop so it return immediately without bothering checking for the other contacts
            break;
        }
    }
   
    return contactFound;
}

 

Link to comment
Share on other sites

Link to post
Share on other sites

Perfect.
Now I get it. And finally got it right.

Thank you both!
You were really helpful!!

This is how the method looks now

    public boolean existeContacto(Contacto c){
      boolean existe= false;
        for (int i=0;i<persona.length;i++){
                if (persona[i]!=null && persona [i].getNombre().equals(c.getNombre())){
                existe=true;
                }
        }
        return existe;
    }

 

I need it to go throught the whole list cuz I need it to either find a existing contact with the same name to send an error message to the user or to send a false to another method to seach for null objects o add the new contact in the phonebook list

I finally understand better this, and got it to work better

Again, thank you both very much for your help, @Franck @Sauron

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×