How to display data in java Arraylist

Asked

Viewed 101 times

0

How I list the information stored in an Arraylist in java?
Follow the code for analysis.

public class Main {
    public static void main(String[] args) {
        Aluno aluno = new Aluno();
        ArrayList<Aluno> array_aluno = new ArrayList<Aluno>();
        for (int cont = 1; cont <= 3; cont++){
            aluno.setNome(JOptionPane.showInputDialog("Insira o nome do aluno: ") );
            aluno.setTelefone(JOptionPane.showInputDialog("Insira o telefone do aluno: ") );
            array_aluno.add(aluno);
        }

        for (int cont = 0; cont <= array_aluno.size() ; cont++){
            System.out.println(array_aluno.get(cont) );
        }
    }   
}
  • 1

    That’s right, which doubt?

  • Hi Giuliana! The program runs, but the three printed results are only the last reported. Ex: Student Data Name = SILVA Phone = (55)9999-9999 (print this same result three times on the screen, ignore the previous ones)

  • The problem with your code is that you created the student object outside of the first one is, and so it is always being overwritten. You need to create it inside the for, so 3 different objects will be created and not just 1.

  • That’s right Giuliana, I put the student object to be created inside the for and it worked. Thanks for the help!

1 answer

2

In class Aluno you can overwrite the toString():

@Override
 public String toString() {
      return ("Nome:"+this.getNome() + " Telefone: "+ this.getTelefone());
 }

And use this structure on main:

public class Main {
    public static void main(String[] args) {
        ArrayList<Aluno> array_aluno = new ArrayList<Aluno>();
        for (int cont = 1; cont <= 3; cont++){
            Aluno aluno = new Aluno();
            aluno.setNome(JOptionPane.showInputDialog("Insira o nome do aluno: ") );
            aluno.setTelefone(JOptionPane.showInputDialog("Insira o telefone do aluno: ") );
            array_aluno.add(aluno);
        }

        System.out.println(array_aluno);
    }   
}

After comment of Articund, moved the creation of Aluno into the for (the object was always being overwritten).

  • Hello! The program ran, but the three printed results were only the last reported. Ex: Student Data Name = SILVA Phone = (55)9999-9999 Student Data Name = SILVA Phone = (55)9999-9999 Student Data Name = SILVA Phone = (55)9999-9999

  • From what I’ve seen, you don’t need for. I’ll remove it from the answer and you say if solved.

  • The problem with this code is that it will not record 3 students, but overwrite the only student object being created.

  • @Articuno, you’re right, I had no attempt.

  • 1

    That’s right, I put the student object to be created inside the for and it worked. Thanks for the help!

Browser other questions tagged

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