Error with Arraylist data display

Asked

Viewed 91 times

1

While recovering data from an arraylist by means of the "for" command, it displays the following message:

inserir a descrição da imagem aqui

Note: I could not identify where the error is. What do you think is wrong?

package listatelefonica;

import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;

public class Principal {

public static void main(String[] args) {

    List<Contato> contatos = new ArrayList<Contato>();
    String nome, 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);
        }

    }

}
  • It would be interesting to add the error in text form too, sometimes some people who could help you, may not be able to view the image, by some kind of restriction.

  • 1

    What you want to show in Optionpane?

1 answer

3


This exit is correct.

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

You can create an implementation of the method .toString() in class Contato to change the output or then pass to the showMessageDialog one string with the information(s) you want to display, it only depends on what is required to display in the 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 information (without implementing the method toString())

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

    JOptionPane.showMessageDialog(null, dados);
}

or, by implementing the 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); 
}
  • Hello Jbueno! Now I understand!! Thank you very much for the support.

Browser other questions tagged

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