How to display information about objects in my ArrayList?

1

I want to create a ArrayList to store information about students (name, typing number and status) but I can not get ArrayListadded the information.

The code I have is the following:

Turma.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?

    
asked by anonymous 29.05.2017 / 20:10

2 answers

3

Try to do it this way:

for (Aluno a : turma) {
    a.getInfo();
}

turma is of type ArrayList and does not have this method. You need to access objects of type Aluno within the list to display correctly.

A detail, within the method getInfo you already call println , not having to call again in this method listaAlunos() .

However, it's more interesting to take responsibility of the Aluno class to print things, leaving it to your main class, so I suggest you change the method to the following:

public String getInfo() {
    return getNome() + " - " + getNMec() + " - " + getEstatuto();
}

With this change, you can use println inside the loop:

for (Aluno a : turma) {
    System.out.println(a.getInfo());
}
    
29.05.2017 / 20:17
4

This is because there is no method getInfo() in class ArrayList and turma is an instance of this class.

You may want to call the getInfo method of each aluno

public void listaAlunos(){
    for (Aluno a: turma) {
        a.getInfo();
    }
} 

See working on repl.it.

    
29.05.2017 / 20:13