Incorrect Output when Printing Array Elements

Asked

Viewed 94 times

1

public class Principal {
    public static void main(String[] args) {
        Turma turma = new Turma("Est. de dados","A1","20191");
        turma.inserirAluno(new Aluno("Anselmo",111));
        turma.inserirAluno(new Aluno("Pedro",222));
        turma.inserirAluno(new Aluno("Joao",333));
        turma.imprimir();
    }

}
public class Aluno {
    String nome;
    int matricula;
    public Aluno(String nome, int matricula) {
        this.nome=nome;
        this.matricula=matricula;
    }
}
public class Turma {
    String nome;
    String codigo;
    String periodo;
    List<Aluno> alunos = new ArrayList<Aluno>();
    public Turma(String nome, String codigo, String periodo) {
        this.nome = nome;
        this.codigo = codigo;
        this.periodo = periodo; 
    }
    public void imprimir() {
        for (Aluno b: alunos) { 
            System.out.println(b);
    }
}
public void inserirAluno(Aluno a) {
    alunos.add(a);
}

}

Exit

Teste.Aluno@1db9742
Teste.Aluno@106d69c
Teste.Aluno@52e922

2 answers

4


When you try to print an object directly, it prints the memory address where the object is allocated... That is, you can’t directly print the b, there are two ways to do this...

1st) In class students you override the method ToString() returning a String concatenated with the data you want... Example:

public String toString(){
   return "Nome: " + this.nome + ", Matricula: " + this.matricula;
}

This within the Student class

Already in the print is just put: b.toString()

2nd) Inform inside the same print b.nome, b.matricula

I think I better make the first shape, but here goes each one!

  • Thanks Friend worked perfectly.

0

'b' is an object("Student"), for you to be able to print the values of each object you must use the toString() method. example: b.toString()

The toString() method you can override by setting a different structure if you want to change the output.

Browser other questions tagged

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