How do I use foreach to print information from an object array? (Java)

1

Good evening!

I have this structure below and would like to know how I could use a for each to print the information for this vector.

public static void main(String[] args) {
    Scanner teclado = new Scanner(System.in);

    Funcionario funcionarios[] = new Funcionario[5];

    String nome;
    double salario;

    for (byte i = 0; i < 2; i++) {
        System.out.println("informe o nome: ");
        nome = teclado.nextLine();

        System.out.println("informe o salario");
        salario = Double.parseDouble(teclado.nextLine());

        Funcionario f;
        f = new Funcionario();
        f.nome = nome;
        f.salario = salario;

        funcionarios[i] = f;
    }

    //Este código abaixo foi uma tentativa, não entendi como ele funciona
    for(Funcionario f1 : funcionarios){
        System.out.println(f1);
    }

    }
    
asked by anonymous 22.08.2016 / 09:09

1 answer

4

Probably, when you run this code, the output looks something like this:

Funcionario@28d93b30

This is unrelated to loop , and occurs because you are printing an object, not primitive types such as int , float , and so on. When you call System.out.println(f1); it will fetch by the toString method of the employee class. Then you think, "I do not have any 'to string' method in this class."

In Java, every class is a subclass of Object implicitly, imagine that there is extends Object even against your will (: P). And if you look at the you will see that object has some methods and toString is one of them, that is, whenever you create a class, this method will be present.

If you do not overwrite the method , then the superclass code will be called. And the implementation of it is as follows:

public String toString() {
   return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

This is the class name followed by the @ and the hexadecimal code of the object's hashcode .

So, responding, you can access the attributes of this object:

for(Funcionario f1 : funcionarios){
   System.out.println("Nome: " + f1.nome + ", Salário: " + f1.salario);
}

Or do what (in my opinion) is much simpler: override the toString method:

public class Funcionario {

    public String nome;
    public double salario;

    @Override
    public String toString(){
        return "Nome: " + nome + ", Salário: " + salario;
    }
}

So by calling System.out.println(f1) the code that was defined in the employee class will run and you will have a "readable" output for humans.

    
22.08.2016 / 11:36