Tenho o seguinte código para teste (linguagem Java):
public class Teste {
static int n = 10;
static int[] vB = new int[10];
public static void exibir(){
for (int i = 0; i < n; i++) {
System.out.print(" " + vB[i]);
}
System.out.println("\n");
}
public static int remover(int chave){
if (n == 0) {
return -1;
}
for (int i = 0; i < n; i++) {
if (vB[i] == chave) {
if (i != (n-1)) { //se não for o último item
for (int k = i; k < (n-1); k++) {
vB[k] = vB[k+1]; //vetor caminha
}
}
n--;
return 1;
}
}
return 0;
}
public static void main(String[] args) {
int valor = 1;
for (int i = 0; i < 10; i++) {
vB[i] = valor;
valor += 2;
}
exibir();
System.out.println("remover(19) = "+remover(19));
if (remover(19) == -1) {
System.out.println("O vetor vB está vazio!");
} else if(remover(19) == 1){
System.out.println("Sucesso! A chave 19 foi removida do vetor vB.");
} else if(remover(19) == 0){
System.out.println("A chave 19 não foi encontrada no vetor vB.");
}
n++;
System.out.println("");
int b = remover(19);
System.out.println("b = "+b);
if (b == -1) {
System.out.println("O vetor vB está vazio!");
} else if(b == 1){
System.out.println("Sucesso! A chave 19 foi removida do vetor vB.");
} else if(b == 0){
System.out.println("A chave 19 não foi encontrada no vetor vB.");
}
}
}
A saída é:
run:
1 3 5 7 9 11 13 15 17 19
remover(19) = 1
A chave 19 não foi encontrada no vetor vB.
b = 1
Sucesso! A chave 19 foi removida do vetor vB.
Em ambos os casos, remover(19) retorna 1. Porém, quando o retorno do método não é atribuído a uma variável int, ele retorna um valor diferente do esperado (esperado por mim), que seria: "Sucesso! A chave 19 foi removida do vetor vB."