If you want to give break
and the return
within the if
, makes no sense. Can’t put anything after a return
. If the problem is just the error that is occurring, just take the break
because the only problem is having a command after the method output. When you exit the method, you certainly came out of the loop.
But it is not enough to remove the 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 kind.
This method is indicating if you found any user who 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 went through the whole loop without falling into the if
. Thus:
class Program {
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;
}
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
There were other errors that prevented the operation. Of course I had to make some adaptations to simplify. Yours would look like this (I think, obviously I didn’t test):
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;
}
But as soon as you return, it leaves the function and the loop.
– mutlei