[RESOLVIDO] Duvidas com toString()

4 respostas
S

Oi
estou querendo saber pq aparece na saida uma parte como se eu não tivesse sobrescrito o toString() ??
aproveitando o espaço, como faço para mostrar no também no metodo toString o sexo do cliente ??
valeu

SAIDA GERADA:

Nome = João
Sexo = class SexoCliente
Matricula = 1
(0) Cliente@42e816
Nome = Marina
Sexo = class SexoCliente
Matricula = 2
(1) Cliente@9304b1
Nome = Jaqueline
Sexo = class SexoCliente
Matricula = 3
(2) Cliente@190d11
Nome = João
Sexo = class SexoCliente
Matricula = 1
(3) Cliente@a90653

DEMAIS CLASSES:

public class Cliente {

	
private String nome;
private int matricula;
	
public Cliente(String nome, SexoCliente sexo, int matricula) {
	this.setNome(nome);
	this.setMatricula(matricula);

}


	public String toString() {
		System.out.println("Nome = " + nome);
		System.out.println("Sexo = " + //SEGUNDA DUVIDA AQUI);
		System.out.println("Matricula = " + matricula);
		return super.toString();
	}
	
	
	//getters and setters omitidos
	
}
	


enum SexoCliente {
	
	MASCULINO, FEMININO;
}
import java.util.LinkedList;


public class Collection {
	
	public static void main(String[] args) {
		
	
	Cliente cliente1 = new Cliente("João", SexoCliente.MASCULINO, 1);
	Cliente cliente2 = new Cliente("Marina", SexoCliente.FEMININO, 2);
	Cliente cliente3 = new Cliente("Jaqueline", SexoCliente.FEMININO, 3);
	Cliente cliente4 = new Cliente("João", SexoCliente.MASCULINO, 1);
	
	LinkedList lista = new LinkedList();
	
	lista.add(cliente1);
	lista.add(cliente2);
	lista.add(cliente3);
	lista.add(cliente4);
	
	for (int i = 0; i < lista.size(); i++){
		System.out.println("(" + i + ")" + " " + lista.get(i));
	}
	
	}

}

4 Respostas

L

Seu método toString já esta imprimindo no console e retornando o toString do pai.

Faz assim:

public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Nome = " + nome + "\n"); builder.append("Sexo = " + sexo.name() + "\n"); builder.append("Matricula = " + matricula + "\n"); return builder.toString(); }

S

lsjunior:
Seu método toString já esta imprimindo no console e retornando o toString do pai.

Faz assim:

public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Nome = " + nome + "\n"); builder.append("Sexo = " + sexo.name() + "\n"); builder.append("Matricula = " + matricula + "\n"); return builder.toString(); }

Hummm, mas teria outro jeito sem precisar instanciar StringBuilder ou StringBuffer ?
e na saida do sexo do cliente, tem como mostrar um resultado de um enum?

L

1 - Só concatenando as String direto.
2 - name() em uma enum retorna o nome, no seu caso MASCULINO ou FEMININO.

S

lsjunior:
1 - Só concatenando as String direto.
2 - name() em uma enum retorna o nome, no seu caso MASCULINO ou FEMININO.

Joia, valeu amigo :smiley: :smiley:

Criado 21 de novembro de 2011
Ultima resposta 21 de nov. de 2011
Respostas 4
Participantes 2