How to view object information from my Arraylist?

Asked

Viewed 509 times

1

I want to create a ArrayList to store information about students (name, number and status) but I’m not getting Arraylistadicione the information.

The code I have is this::

Java class.

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

4

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

Maybe you want to call the method getInfo of each aluno

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

See working on repl.it.

3


Try to do it this way:

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

turma is the type ArrayList and does not have this method. You need to access the type objects Aluno inside the list to be displayed correctly.

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


However, it is more interesting to take the class responsibility Aluno 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, then you can use the println within the loop:

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

Browser other questions tagged

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