insert multiple objects into an object array

Asked

Viewed 365 times

0

When I insert the next object it returns a Boolean false

public class Main {

    static Aluno aluno = new Aluno();
    static Scanner s = new Scanner(System.in);
    static RepositorioA repositorioA = new RepositorioA();

    public static void main(String[] args) {
        Main main = new Main();

        main.menuPrincipal();
    }

    public void cadastrarAluno() {

        System.out.println("Nome: ");
        aluno.setNome(s.next());
        System.out.println("Cpf: ");
        aluno.setCpf(s.next());

        if (repositorioA.inserirAluno(aluno) == true) {
            System.out.println("Aluno cadastrado!");
        } else {
            System.out.println("Falha no cadastro!");
        }
        menuAluno();
    }

    public void menuAluno() {
        int escolha = 0;

        System.out.println("1-Cadastrar");
        System.out.println("2-Voltar");
        escolha = s.nextInt();

        switch (escolha) {
        case 1:
            cadastrarAluno();
        }

    }

    public void menuPrincipal() {
        int opcao = 0;

        do {
            System.out.println("Escolha uma opção");
            System.out.println("1 - Menu Aluno");
            opcao = s.nextInt();

            switch (opcao) {
            case 1:
                menuAluno();
            default:
                opcao = 0;
            }
        } while (opcao != 0);
    }
}

public class RepositorioA {
    Aluno[] listaAluno = new Aluno[100];

    public boolean inserirAluno(Aluno aluno) {
        // Procura clientes com o mesmo CPF na lista
        for (int i = 0; i < listaAluno.length; i++) {
            if (listaAluno[i] != null && listaAluno[i].getCpf().equals(aluno.getCpf())) {
                return false;
            }
        }

        // Procura um espaço vazio
        for (int i = 0; i < listaAluno.length; i++) {
            if (listaAluno[i] == null) {
                listaAluno[i] = aluno;
                return true;
            }
        }

        // LISTA CHEIA
        return false;

    }

}

1 answer

2


The problem is that you are always modifying the same student. This is because the only time you instate a student is at the beginning of the program (when Voce makes a new Student()).

To correct this, please prompt a new student when you enter the registration method:

  public void cadastrarAluno() {

        aluno = new Aluno(); // insira essa linha no seu codigo

        System.out.println("Nome: ");
        aluno.setNome(s.next());
        System.out.println("Cpf: ");
...
  • Hi Dan, if this answer solved your problem, please mark as correct. A strong hug

  • It helped a lot, thanks

Browser other questions tagged

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