3
I am a beginner in Java and my teacher passed a list of exercises to practice, in a question I need to create a system that registers a user only if his email has not been registered before.
A part of the User class is like this (it is abstract because there are several types of user):
public abstract class Usuario {
private String email;
private String nomeCompleto;
private LocalDate dataNascimento;
public Usuario(String email, String nomeCompleto, LocalDate dataNascimento) {
this.email = email;
this.nomeCompleto = nomeCompleto;
this.dataNascimento = dataNascimento;
}
public String getEmail() {
return email;
}
I created a repository to "register" users in an Arraylist, which was like this:
public class RepositorioUsuario {
private ArrayList<Usuario> usuarios = new ArrayList<>();
public void cadastrarUsuario(Usuario u) {
for (Usuario a : this.usuarios) {
if (u.getEmail().equals(a.getEmail())) {
usuarios.add(u);
}
}
}
The part that doesn’t work at all is this, specifically the verification.
for (Usuario a : this.usuarios) {
if (u.getEmail().equals(a.getEmail())) {
usuarios.add(u);
}
}
If I take out the for and if, the user is added smoothly (I created a method to list them).
My question is, because the way I did it’s not working?