Error with data display ArrayList

1

When retrieving data from an arraylist via the "for" command, it displays the following message:

Note:Icouldnotidentifywheretheerroris.Whatdoyouguysthinkiswrong?

packagelistatelefonica;importjava.util.ArrayList;importjava.util.List;importjavax.swing.JOptionPane;publicclassPrincipal{publicstaticvoidmain(String[]args){List<Contato>contatos=newArrayList<Contato>();Stringnome,telefone,email,opcao=null;do{nome=JOptionPane.showInputDialog(null,"Informe o nome:");
        telefone = JOptionPane.showInputDialog(null,"Informe o telefone:");
        email = JOptionPane.showInputDialog(null,"Informe o email:");

        Contato contato = new Contato(nome,telefone,email);
        contatos.add(contato);
        opcao = JOptionPane.showInputDialog(null,"Digite N para criar um novo contato ou outra tecla para encerrar:");
    } while (opcao.toUpperCase().equals("N"));


        for (Contato umContato : contatos){
            JOptionPane.showMessageDialog(null, umContato);
        }

    }

}
    
asked by anonymous 17.04.2017 / 19:02

1 answer

3

This output is correct.

The second parameter of JOptionPane.showMessageDialog will be converted to string and this is the default implementation of .toString() in class Object (all classes inherit from Object in Java) .

You can create an implementation of the .toString() method in the Contato class to change the output or else move to showMessageDialog a string with the information (s) you want to display, this only depends of what you need to show in OptionPane .

Examples:

Showing only the name of the contact.

for (Contato umContato : contatos){ 
    JOptionPane.showMessageDialog(null, umContato.getNome()); // Mostra o nome do contato
}

or, showing all contact info (without implementing the toString() method)

for (Contato umContato : contatos){ 
    String dados = umContato.getNome() + ", " + 
                   umContato.getTelefone() + ", " + 
                   umContato.getEmail();

    JOptionPane.showMessageDialog(null, dados);
}

or, doing the implementation of toString()

public class Contato {
    // Entre outras coisas

    public String toString() {
        return this.nome + ", " + this.telefone + ", " + this.email;
    }
}
for (Contato umContato : contatos){ 
    JOptionPane.showMessageDialog(null, umContato); 
}
    
17.04.2017 / 19:19