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) );
}
}
}
That’s right, which doubt?
– Giuliana Bezerra
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)
– Jordan
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.
– Giuliana Bezerra
That’s right Giuliana, I put the student object to be created inside the for and it worked. Thanks for the help!
– Jordan