Doubt in Arrays - Beginner

Asked

Viewed 391 times

3

How do I make the method mostraEmpregados print on screen the name of the employees I’ve already added?

How to build the array within the Enterprise class statement itself, making it every time a Empresa is instantiated, the array of Funcionario that she needs is also created?

package meu.programa;

public class Funcionario {
    String nome;
    String departamento;
    double salario;
    Data dataDeEntrada;
    String rg;
    boolean estaNaEmpresa = true;

    void recebeAumento(double valorDoAumento) {
        salario += valorDoAumento;
        System.out.println("O salario atual do funcionario " + this.nome + " eh: " + this.salario);
    }
    void calculaGanhoAnual () {
        double ganho = salario * 12;
        System.out.println("O ganho anual do funcionario " + this.nome + " eh: " + ganho);
    }
    void demite () {
        if (this.estaNaEmpresa == true) {
            this.estaNaEmpresa = false;
            System.out.println("O funcionario " + this.nome + " foi demitido ...");
        }
        else {
            System.out.println("O funcionario ja foi demitido ...");
        }
    }
    void mostra () {
        System.out.println("Nome: " + this.nome);
        System.out.println("Departamento: " + this.departamento);
        System.out.println("Salario: " + this.salario);
        System.out.println("Data de entrada na empresa: " + this.dataDeEntrada.dataFormatada());
        System.out.println("RG: " + this.rg);
        System.out.println("É funcionario da empresa: " + this.estaNaEmpresa);

    }
}

.

class Empresa {
    String nome;
    String cnpj;
    Funcionario[] empregados;

    void adiciona(Funcionario f) {
        int contador = 0;
        this.empregados[contador] = f;
        contador++;
        if(contador == this.empregados.length) {
            System.out.println("A array está cheio ...");
        }

    }

    void criaArray (int n) {
        this.empregados = new Funcionario [n];

    }
    void mostraEmpregados() {
        for (int i=0; i <= this.empregados.length; i++) {
            System.out.print("Funcionario na pos.: " + i);
            System.out.println(" Nome:" + this.nome);
        }
    }
}

And another class to test the Company class:

package meu.programa;

public class TestaEmpresa {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Empresa empresa = new Empresa();
        empresa.criaArray(5);

        Funcionario f1 = new Funcionario();
        f1.nome = "Victor";

        Funcionario f2 = new Funcionario();
        f2.nome = "Guilherme";

        empresa.adiciona(f1);
        empresa.adiciona(f2);

        empresa.mostraEmpregados();
    }

}

3 answers

3

Is this some exercise, or is it to be used in practice?

If it is exercise, your problem is that when you create an array in empresa.criaArray(5) it will create an array with 5 positions, all of them filled with null. Thus, you can find out if there is "space" in the array by testing whether each of these elements is null. The first null that you find, use this index to store your Funcionario. If you go through the entire array and find no position with null, is because the array is full (there you see what is best to do - throw an exception, create a new array...)

In the same way, your mostraEmpregados is traversing the entire array, so it will give problem if find null elements. I suggest testing each of them before trying to print.

Now, if it’s to be used in practice, the ideal is to use java.util.ArrayList (or something similar, as pointed out in the carlospheric response).

  • It’s just an exercise. Thank you !

2

The location to initialize the employee array would be on builder class Enterprise, which is called every time an object of this class is created:

class Empresa {
    // ...
    public Empresa(int numeroDeEmpregados) {
        this.empregados = new Funcionario[numeroDeEmpregados];
    }
    // ...
}

Now, this solution is a bit restricted - when the company is created you need to know the number of employees, but this is not common. Furthermore, a company may have a variable number of employees (fired / hired), so the array is not the most appropriate data structure for this - java arrays have a fixed size. A suggestion is to use a List (for example, ArrayList) that can grow dynamically depending on the need.

2

for (int i=0; i <= this.empregados.length; i++) {
    System.out.print("Funcionario na pos.: " + i);
    System.out.println(" Nome:" + this.nome);
}

@Victor, the this that you use in line 3 of the visualization method, refers to the instance of the class itself, that is, the reference will print the name of the company, while, I believe, what you expect is the name of the employee. The correction would be System.out.println(" Nome:" + empregados[i].nome); because it references the correct instance of Funcio that is contained in the vector, through the for counter.

I believe this would work!

I put your code to work here, and returned what I really hoped... It prints Funcionario na pos.: i Nome: Nome dado à empresa. After this I realized that your is of the shown method Jobs is a little misguided. Realize, the value of the length, or even of the function length(), if they are Lists, returns the array’s element # however, the vectors in general treat the position of their element from position 0. So, if the array contains 1 element, it will have length = 1, and position = 0. As you put it in the method, it would give an Arrayindexoutofbounds, since it would try empregados[5] where 5 is the length of the vector, while the vector could only go up to 4, since it would have the values of 0, 1, 2, 3 and 4. Then it would be right to put < in place of <=.

But that’s it. Since I know it’s an exercise, I know that you will use Lists Then take your time. I would advise, as the people above said, to initialize the size of the vector in the constructor itself, to be more coherent, rather than calling a method that would zero the vector and place a new clean vector in place, losing the previous values... Hey, would it be cool if you made that method of criaArray were a expandeArray creating a new array, and copying the old values to the new one! It would be nice also if the mostraEmpregados() called straight the mostra() of the employee class, because then you would have the complete information of the employees.

Browser other questions tagged

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