What is the behavior of a method that returns integer within the if?

Asked

Viewed 65 times

1

I have the following test code (Java language):

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.");
    }

}
}

The exit is:

 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.

In both cases, remove(19) returns 1. However, when the return of the method is not assigned to an int variable, it returns a different value than expected (expected by me), which would be: "Success! Key 19 has been removed from Vb vector."

2 answers

2

When you do not assign the return of the method to a variable, as here:

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.");
}

It turns out that it is calling remove potentially 4 times, depending on the value it returns.

It is first called in the System.out:

System.out.println("remover(19) = "+remover(19));

And soon after called on if:

if (remover(19) == -1) {

And in this case as the element has already been removed will give 0 that did not find the value in the vector, and will continue to call in the other ifs until hit the last one, which is the result shown when the program runs:

1 3 5 7 9 11 13 15 17 19

remove(19) = 1

Key 19 was not found in vector Vb.

In this type of situations the way it was done in the second block is exactly what is intended:

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.");
}

Thus keeping the result in a guaranteed variable that only uses it and does not call the same method over and over again.

0


Watch this excerpt:

    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.");
    }

In the first System.out, it removes the number 19. No if, it tries to remove the 19 again, and as it does not think (because it has removed before) and results in 0, it does not enter the block of the if and falls into the first else. In that else, it tries to remove a third time, and as it does not find (results in 0), it falls on the last else. He then tries to remove a fourth time and as this time the result again is 0, it shows the message.

In short, this code that is there is equivalent to this:

    int resultado1 = remover(19);
    System.out.println("remover(19) = " + resultado1);

    int resultado2 = remover(19);
    if (resultado2 == -1) {
        System.out.println("O vetor vB está vazio!");
    } else {
        int resultado3 = remover(19);
        if (resultado3 == 1) {
            System.out.println("Sucesso! A chave 19 foi removida do vetor vB.");
        } else {
            int resultado4 = remover(19);
            if (resultado4 == 0) {
                System.out.println("A chave 19 não foi encontrada no vetor vB.");
            }
        }
    }

The problem is you’re calling remover(19) several times in the if. You should just call one. What you want is this:

    int resultado = remover(19);
    System.out.println("remover(19) = " + resultado);
    if (resultado == -1) {
        System.out.println("O vetor vB está vazio!");
    } else if (resultado == 1) {
        System.out.println("Sucesso! A chave 19 foi removida do vetor vB.");
    } else if (resultado == 0) {
        System.out.println("A chave 19 não foi encontrada no vetor vB.");
    }

And that’s exactly what you do in the next block below.

  • Putz... I need to get some sleep... what a silly thing... thanks Victor!!

  • @Joãopaulorolim If you have no further doubt about this question, click on what appears below the voting number of this answer (or the other if you prefer) to mark it as accepted and mark your question as resolved. If you still have any questions, feel free to comment. It was a pleasure to help you.

Browser other questions tagged

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