Break inside method that returns boolean

3

I'm trying to make a loop for , which at one time returns true , and exits the loop.

Example:

public boolean autentica (Usuario usuario) {
    for(i=0; i<listaUsuarios.size ; i++){
        if(usuario.getSenha().equals(listaUsuarios.get(i).getSenha()){
            return true;
            break;
        }
    }
}

That is, when something happens, return true and exit the loop, because it will not continue testing the password on other users.

In short, I want to return true and exit the loop. How do I do? Well, that's a mistake.

    
asked by anonymous 28.01.2015 / 12:50

2 answers

5

If you want to give break and return within if , it does not make sense. You can not put anything after a return . If the problem is just the error that is occurring, just take break because the only problem is having a command after the method exit. When you exit the method, you have certainly left the loop.

But do not just remove break . You will still have an execution path that will return nothing. You need to return a boolean every time. The code needs to ensure that in all situations it returns something of the same type.

This method is indicating if you have found a user that has authenticated, I think you want to inform if you did not authenticate also if you do not find any user with password compatible, then just put a return false at the end of the method if it passed the whole loop without falling into if .Thus:

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone {
    static String[] listaUsuarios = new String[] { "1", "12", "123" };
    public static void main (String[] args) throws java.lang.Exception {
        System.out.println(autentica("123"));
        System.out.println(autentica("456"));
    }
    public static boolean autentica (String usuario) {
        for(int i = 0; i < listaUsuarios.length; i++) {
            if(usuario.equals(listaUsuarios[i])) {
                return true;
            }
        }
        //opcionalmente faz alguma coisa aqui.
        return false;
    }
}

See running on ideone . There were other errors that prevented the operation. Of course I had to make some adjustments to simplify. Yours would look like this (I think, obviously I have not tested):

public static boolean autentica (Usuario usuario) {
    for(int i = 0; i < listaUsuarios.length; i++) {
        if(usuario.getSenha().equals(listaUsuarios.get(i).getSenha()) {
            //opcionalmente faz alguma coisa aqui.
            return true;
        }
    }
    //opcionalmente faz alguma coisa aqui.
    return false;
}
    
28.01.2015 / 13:07
1

The return anywhere that ends the method (and therefore the loop). The error you should be encountering is that break is dead code, never reached, because the method will always return before reaching it. Remove% w / w which should work.

    
28.01.2015 / 13:05