Command is not working

Asked

Viewed 44 times

-2

I have a code to remove an index that was typed by the user, only it is not working properly, it erases two values when it was to delete a single one, or else it erases a position that was not correct

public double remove(int K) {
    double remover = 0;
    if(!(K>=0 && K <size())) {
        System.out.println("Posição invalida!");
    }

    for(int k=K;k< size()-1;k++) {
        remover =vet[K]= 0;
    }
        
    return remover;
}
  • 1

    The logic of the removal loop is wrong, the variable "remove" is useless and the core should be something like "vet[k] = vet[k+1]".

  • Excuse the question, but could you explain to me better? It’s my first time in programming and I’m having some difficulties

  • I’ll put it in the answer anyway

1 answer

1

The block that eliminates the item should be something like:

remover = vet[K];
for(int k = K; k < size() - 1; k++) {
    vet[k] = vet[k+1];
}

The idea is to do a "chair dance", eliminating item K by copying the item from position K+1 on top of it, and then doing the same for all forward positions. If the vector was

a b c d e f

and want to remove position 2 (assuming vet[0] equal to "a"), the above loop moves the array like this at each cycle:

a b c d e f   (antes)
a b d d e f   (k = 2)
a b d e e f   (k = 3)
a b d e f f   (k = 4)

Once this is done, to discard the final element, the size of the vector can be decreased by 1. It is not clear how to do this in your program because the question does not show the implementation of the size() function, so it is not clear whether the size is stored in a variable, etc.

What his original block did was just assign 0 to the position element to be eliminated, without moving the rest of the places.

Browser other questions tagged

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