How do I display object information from my ArrayList?
I want to create a ArrayList
to store information about students (name, typeset number and status) but I'm not getting ArrayList to add the information.
The code I have is as follows:
Flock.java
package turma;
public class Aluno {
public String nome;
public int nmec;
public String estatuto;
public Aluno(int nmec, String nome) {
this.nome = nome;
this.nmec = nmec;
estatuto = "Regular";
}
public String getNome() {
return nome;
}
public int getNMec() {
return nmec;
}
public String getEstatuto() {
return estatuto;
}
public void getInfo() {
System.out.print(getNome() + " - " + getNMec() + " - " + getEstatuto());
}
}
TurmaMax.java
package turma;
import java.util.ArrayList;
/**
*
* @author Z
*/
public class TurmaMax {
public ArrayList<Aluno> turma;
private int i;
public TurmaMax() {
turma = new ArrayList<Aluno>();
}
public void novoAluno (int nmec, String nome){
if(turma.size() < 30) {
turma.add(new Aluno(nmec,nome));
} else {
System.out.print("Turma cheia");
}
}
public void listaAlunos(){
for (i=0; i<turma.size(); i++) {
System.out.println(turma.getInfo()); // o erro acontece nesta linha
}
}
}
What's wrong with my code?
2 answers
Try to do the for like this:
for (Aluno a : turma) {
a.getInfo();
}
turma
it is of type ArrayList
and does not have this method. You need to access objects of type Aluno
within the list for it to display correctly.
A detail, inside the method getInfo
you already call the println
, having no need to call again in this method listaAlunos()
.
However, it is more interesting to take the responsibility of the Aluno
class to print things, leaving it to its main class, so, I suggest you change the method to the following:
public String getInfo() {
return getNome() + " - " + getNMec() + " - " + getEstatuto();
}
With this change, ai you can use the println
inside the Loop:
for (Aluno a : turma) {
System.out.println(a.getInfo());
}
This is because there is no method getInfo()
in class ArrayList
and turma
is an instance of this class.
You might want to call the getInfo
method of each aluno
public void listaAlunos(){
for (Aluno a: turma) {
a.getInfo();
}
}