Method with foreach only returns false

Asked

Viewed 123 times

4

I have a method that will check whether the debt is equal to zero(divida == "0"). If it is he returns true, else it returns false.

Code:

    for(String divida : dividas){
        return divida == "0";
        System.out.println(divida+"\n"+b);
    }
    return false;

He only returns false, why the first element is non-zero, but the second is equal, and remains false.

What I do?

1 answer

11


You must use the equals to compare the contents of the string, the == test the reference.

    for(String divida : dividas){
        return (divida.equals("0"))

Want to understand more about comparisons in Java?
Give a read on this question and its answers: Behavior of different ways of comparison in Java.

Adding code as per comment:

    boolean retorno = false;
    for(String divida : dividas){
        if(retorno = divida.equals("0")) {
            break;
        }
    }       
    return retorno;
  • It continues the same way if the first element (or the one before) is non-zero returns all false.

  • I understood where the error was, is that every time I went to check if it was equal to zero I just checked the first and returned, And the same process always happened.

  • @lucasdaniel added a block

  • But if it returns false it will execute another code.

  • I would put return true; inside the block of if and return false; out. With this I do not fall into the bad practice of programming to assign the variable in the condition of the if and I don’t even need that variable. I also don’t need break;.

Browser other questions tagged

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