system with CRUD

Asked

Viewed 132 times

1

I am majoring in Systems and I am developing a system, and my difficulty is to remove an element array, because the problem in question is that when there is more than one element it removes normally, but when there is only one element it does not remove, my logic used for removal must have some error, because I am not able to solve the problem.

follows below the code I am making

public int buscarImovel(int cod){
    for(int i = 0; i < qtdImoveis; i++) {
        if(imoveis[i].codigo == cod)
            return i;
    }
    return -1;
 }
public void deletarImovel(int cod){ 
    int i = buscarImovel(cod);

    if(i >= 0){
        for(int j = i; j < qtdImoveis-1; j++){
            imoveis[j] = imoveis[j + 1];
            qtdImoveis--;
            imoveis[qtdImoveis] = null;

            if(imoveis[j].codigo != cod)
                System.out.println("Não foi encontrado o imóvel com código informado");
        }
    }
}
  • Good morning, buddy. Could you go into more detail? ...

  • Without showing us your code we have no way to help you. Another thing: If you need to insert and remove elements, you should consider using a ArrayList in place of a normal array.

  • was bad, I just edited it is because I had never sent a question before

1 answer

2


Look at your logic:

for(int j = i; j < qtdImoveis-1; j++){
    imoveis[j] = imoveis[j + 1];
    qtdImoveis--;
    imoveis[qtdImoveis] = null;
}

If the array has 1 element and you want to remove this single element, the loop for above will have the following values:

for(int j = 0; j < 1-1; j++)

Clearly you realize that the loop will never run because j is 0 and 0 is never less than 1-1.

I strongly suggest you use the class Arraylist because it has a specific method to remove an element. Simply call:

imoveis.remove(i);

And the element in the index iwould be removed.

Browser other questions tagged

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