Error when assigning object to another class

Asked

Viewed 42 times

0

In the code it arrow the values of the employees with the first entered value and ignores the others.

for(int i=0; i<3; i++) {
            Empregados f = new Empregados();
            System.out.println("Qual é o salario do "  + (i+1) + " empregado? ");
            f.salario = entrada.nextDouble();
            f.numero = i + 1;
            e.adiciona(f);
        }

which error in the method?

company class:

public class Empresa {

    String nome;
    String localidade;
    Empregados[] empregados;
    int numFuncionarios;

    Empresa(String nome, String localidade) {
        empregados = new Empregados[3]; 
        numFuncionarios = 0;
        this.nome = nome;
        this.localidade = localidade;

    }

    void adiciona(Empregados e) {
        while(numFuncionarios < 3) {
            empregados[numFuncionarios] = e;
            numFuncionarios++;
        }

    }

    void mostraDadosEmpresa() {
        System.out.println("Nome: " + this.nome);
        System.out.println("Localidade: " + this.localidade);
        for(int count=0; count < empregados.length; count ++) {
            System.out.println("Empregado n." + (count + 1) + "salario: " + empregados[count].getSario());
        }

    }


}
  • What is this variable e?

  • company name: Company e = new Company();

  • It has only two variables, the salary and number

  • Company is a list? Add the implementation of it in question too, and of class employees.

1 answer

1


The loop of your method adiciona() will always add a single employee in the three positions, and every time you add another employee, the loop will add that employee over the three positions again. To resolve, remove the loop and use a condition if:

void adiciona(Empregados e) {
    if(numFuncionarios < 3) {
        empregados[numFuncionarios] = e;
        numFuncionarios++;
    }
}

Browser other questions tagged

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