1
I created a class Funcionário
, and in class Main
create an array
of objects of this type. I am now trying to set the attribute "position" of employees in a loop, but gives NullPointerException
...
"NOTE: THE PROBLEM REFERRED TO IN THIS QUESTION IS ABOUT THE NEED TO OBJECT CREATION FOR EACH INDEX OF AN OBJECT ARRAY."
Set method in Employee class is simple:
public void setCargo(String cargo) {
this.cargo = cargo;
}
This is the code on main:
Funcionario[] funcis = new Funcionario[5];
Scanner ler = new Scanner(System.in);
int x=0;
System.out.println("Informe os cargos: ");
for(x=0; x<funcis.length; x++){
funcis[x].setCargo("testa"); //AQUI DA EXCEPTION NULLPOINTER
}
To top it off: When creating the Employees array, am I already allocating an Employee object to each position on that array? Or I just reserved the memory space?
– Lucas Pletsch
You created an array but did not create Employees and did not insert them into the array, which is why it gives Nullpointerexception.
– Douglas
You would have to do something like: funcis[x] = new Employee(); inside a For then?
– Lucas Pletsch
It worked out! Thanks!
– Lucas Pletsch