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;
}