What is wrong with this method?

Asked

Viewed 86 times

1

I’m doing a method of adding Users, and just one thing isn’t working, the function that:

"Adding friends with the same mobile number will not be allowed."

Ai need to check the users already added, to see if they do not have a mobile number equal to the one that is added.
It’s adding, but it’s also adding users with the same mobile number. And it couldn’t add if the number was equal

inserir a descrição da imagem aqui

 public void AdicionaAmigo(Usuario usr)
    {
       boolean existeEsteNum = false;
       if(ListadeAmigos == null || ListadeAmigos.length == 0) { 

         for(int i=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");
           }
       }
    }
  • 2

    Please add the code in text form to make it easier to test.

  • And what is the error that returns?

  • 1

    And report what is not working. What happens? Under what circumstances?

  • It’s adding, but it’s also adding users with the same mobile number. And it couldn’t add if the number was equal.

  • The part of checking the phone is not working, it adds anyway users;

2 answers

4


What is wrong in this method, is that you are going through the "go" if the list is empty, so it will not fall in condition ever.

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

if ( ListadeAmigos != null && ListadeAmigos.length > 0 ) 
  • I just tried to do so, gave the error message "java.lang.Nullpointerexception: null" and marking if in yellow(Listadeamigos[i]. getCel() == usr.getCel()){

  • So see if usr is null or has any position in the list that is null. The answer is correct.

  • @Daniel, when you are not sure if you have value filled in, you should never access directly, because it will cause nullPointerException, check before accessing getCel() if the use or Listmigos[i] is not null

  • I understand the logic. But how can I?

  • if ( ( usr != null && Listmigos[i] != null) && Listmigos[i]. getCel() == usr.getCel() )

  • First you check if there are objects (not null) and then check if the cell phones are equal

  • It worked perfectly! Thank you very much!

Show 2 more comments

0

  • Thanks for the tip!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.