What's wrong with this method?

1

I'm making a method of adding Users, and only one thing is not working, the function that:

  

"You will not be allowed to add friends with the same mobile number."

Then you need to check the users already added, to see if they do not have a cell number equal to the one added. It's adding, but it's also adding users with the same cell number. And could not add if the number were equal

publicvoidAdicionaAmigo(Usuariousr){booleanexisteEsteNum=false;if(ListadeAmigos==null||ListadeAmigos.length==0){for(inti=0;i<ListadeAmigos.length;i++){if(ListadeAmigos[i].getCel()==usr.getCel()){existeEsteNum=true;System.out.println("Já existe um usuário cadastrado com esse número de celular");
                break;
                }
         }
       } 

       if(!existeEsteNum){
           if(qtdeAmigos < ListadeAmigos.length)
           {
            ListadeAmigos[qtdeAmigos++] = usr;
            System.out.println ("Usuario adicionado com sucesso!");
           } else {
            System.out.println ("A lista está cheia");
           }
       }
    }
    
asked by anonymous 07.06.2017 / 15:44

2 answers

4

What is wrong with this method is that you are traversing "for" if the list is empty, so it will not fall into the condition ever.

What you should do is review the first IF the correct one would be:

if ( ListadeAmigos != null && ListadeAmigos.length > 0 ) 
    
07.06.2017 / 15:50
0

You can change this "==" in if ListadeAmigos[i].getCel() == usr.getCel() to equals (), I think it would look better, "==" tests the reference, not the value. That would be the first thing I saw right away, I'm going to take another look and see if I can find something. This is an example and explanation of these comparisons

    
07.06.2017 / 16:10