system with CRUD

1

I'm graduating in Systems and I'm developing a system, and my difficulty is to remove an element from an array, because the problem in question is that when it has more than one element it normally removes, but when it has one it does not remove, my logic used for removal should have some error as I can not solve the problem.

Below is the code I'm doing

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");
        }
    }
}
    
asked by anonymous 11.12.2017 / 15:53

1 answer

2

See 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 be executed, because j is 0 and 0 is never less than 1-1 .

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

imoveis.remove(i);

And the element at index i would be removed.

    
11.12.2017 / 16:09