Reputation: 3
I have the class Empresa and the class Funcionario, and when i'm trying to add a salary to a employee, it compile but don't work. here the codes:
Funcionario:
class Funcionario{
String departamento;
String dataEntrada;
String rg;
String nome;
String ferias;
double salario;
void recebeAumento(double aumento){
this.salario += aumento;
}
double calculaGanhoAnual(){
this.salario = salario * 12;
return salario;
}
void mostra(){
System.out.println("Nome: " + this.nome);
System.out.println("Salário: " + this.salario);
System.out.println("Departamento: " + this.departamento);
System.out.println("RG: " + this.rg);
System.out.println("Data de admissão: " + this.dataEntrada);
System.out.println("Ganho anual: " + calculaGanhoAnual());
}
}
class Empresa{
String nome;
String cnpj;
Funcionario [] empregados = new Funcionario[10];
void adiciona(Funcionario func){
for(int i = 0; i < empregados.length; i++){/*i começa da posição 0 e tera o tamanho da
array empregados*/
if(empregados[i] == null){//se a posição estiver vazia
empregados[i] = func; /* a array recebe o valor de func que for adicionado pelo
metodo void*/
break;
}
}
}
void mostraEmpregados(){
Funcionario func = new Funcionario();
for(int i = 0; i < this.empregados.length; i++){
System.out.println("Funcionário na posição: " + i);
System.out.println("Salário do funcionário: " + func.salario);
}
}
}
And the Test class:
class TestaEmpresa{
public static void main (String [] args){
Empresa emp = new Empresa();
emp.empregados = new Funcionario[10];
Funcionario func = new Funcionario();
for(int i = 0; i < 5; i++){
func.salario = 1000.0 + i * 100;
emp.adiciona(func);
}
emp.mostraEmpregados();
}
}
After running the test, i get the position of the array and the salary null, like this:
Funcionário na posição: 0
Salário do funcionário: 0.0
Funcionário na posição: 1
Salário do funcionário: 0.0
Funcionário na posição: 2
Salário do funcionário: 0.0
Funcionário na posição: 3
Salário do funcionário: 0.0
Upvotes: 0
Views: 47
Reputation: 11
the error is in your print method
void mostraEmpregados(){
Funcionario func = new Funcionario();
for(int i = 0; i < this.empregados.length; i++){
System.out.println("Funcionário na posição: " + i);
System.out.println("Salário do funcionário: " + func.salario);
}
}
change it for
System.out.println("Funcionário na posição: " + i);
System.out.println("Salário do funcionário: " + this.empregados[i].salario);
you don't need that object Funcionario func = new Funcionario();
Upvotes: 1
Reputation: 393831
You are not retrieving elements from the array.
System.out.println("Salário do funcionário: " + func.salario);
should be
System.out.println("Salário do funcionário: " + this.empregados[i].salario);
In addition, you should probably make sure that this.empregados[i]
is not null before accessing this.empregados[i].salario
.
Upvotes: 1