Como criar um metodo ToString?

14 respostas
V

Estou fazendo uma programinha, já consegui é converte um double para uma string utilizando o toString, mais eu preciso criar um metodo toString no meu programa oq devo fazer?

14 Respostas

T

cara num é melhor usar o valueOf nao?

String.valueOf();

V

Sim mais sou estagiaria e o meu chefe pediu isso, agora tenho que fazer, alguem pode me ajudar como criar um metodo tostring

Roger75

Você está usando Eclipse? Tem uma opção de menu lá que já gera isso pra você, na sua classe.

T

poe o nome da variavel “.toString”

tipo

int num = 3

System.out.println(num.toString());

Master.Abs
double valor = 2.1;
	
	public String toString(){
		return "Valor: " + valor;
	}

Veja se te ajuda.

romarcio
public class TestToString {
    private String descricao;
    private Double valor;

    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }

    public void setValor(Double valor) {
        this.valor = valor;
    }

    @Override
    public String toString() {
        return "TestToString{" + "descricao=" + descricao + ", valor=" + valor + "}";
    }

    public static void main(String[] args) {
        TestToString tts = new TestToString();
        tts.setDescricao("R$ ");
        tts.setValor(129.65);

        System.out.println(tts.toString());
    }
}

Quando você cria um método toString(), você acaba sobrescrevendo o método toString() original da classe.

Agora o método toString() da classe Double, que deve ter sido o que você usou, é assim:
/**
     * Returns a string representation of this <code>Double</code> object.
     * The primitive <code>double</code> value represented by this
     * object is converted to a string exactly as if by the method
     * <code>toString</code> of one argument.
     *
     * @return  a <code>String</code> representation of this object.
     * @see java.lang.Double#toString(double)
     */
    public String toString() {
	return String.valueOf(value);
    }
Onde é usado o método String.valueOf() para transformar o Double em uma String.
V

na realidade é para eu sobreescrever o metodo ToString?? como eu faço isso?

prog.tiago

Oi, bom dia!

Se importaria de postar o seu código, assim eu consigo fazer para ti e esclarecer melhor sua dúvida. :smiley:

V

package Frame;

import javax.swing.<em>;

import javax.swing.event.</em>;

import java.awt.<em>;

import java.awt.event.</em>;

import java.util.*;

public class ExemploFrame extends JFrame implements ActionListener

{ 	                private JButton b1;

private JTextField t1;

private JTextField t;

private JTextField r;

private JFrame Janela;

private JLabel labelNome;

private JLabel labelNome1;

private JLabel labelNome2;
public static void main(String args[])
	
	{
		new ExemploFrame();
		

	}  	  
	  		
	public ExemploFrame()
	{
	  			  		  	   	      
  	 	labelNome = new JLabel ("Quantidade: ");
		labelNome.setLocation(10,10 );
		labelNome.setSize(100, 30);
			
		t = new JTextField();
		t.setLocation(90, 10);
		t.setSize(100, 30);
	
		labelNome1 = new JLabel ("Taxa: ");
		labelNome1.setLocation(10, 70);
		labelNome1.setSize(100, 30);
			
				  
		t1 = new JTextField();
		t1.setLocation(90, 70);
		t1.setSize(100, 30);
		
		labelNome2 = new JLabel ("Resultado: ");
		labelNome2.setLocation(10,130 );
		labelNome2.setSize(100, 30);
	
	   	r = new JTextField();
		r.setLocation(90, 130);
		r.setSize(100, 30);
		
				 
		b1 = new JButton("Calcular");    
		b1.setLocation(10,190 );
		b1.setSize(110, 30);
		b1.addActionListener(this);
	 
		Janela = new JFrame();
	 	Janela.setTitle("Digite os dados ");  			
		Janela.setLayout(null);
	 	Janela.add(t);
	 	Janela.add(t1);
	 	Janela.add(labelNome);
	 	Janela.add(labelNome1);
	 	Janela.add(labelNome2);
	 	Janela.add(b1);
	 	Janela.add(r);
	 	Janela.setLocationRelativeTo(null);
	 	Janela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	 	Janela.setSize(300,300);
	 	Janela.setVisible(true);		
	 	Janela.show();	
	
	}
		public void actionPerformed(ActionEvent e)
	{	           
                                 if (e.getSource()== b1)
		
		{
			String quantidade  = this.t.getText();
			
	        		Double qt = Double.parseDouble(quantidade);
			
			String taxa = this.t1.getText();
			Double tx = Double.parseDouble(taxa);
			
			Double calculo = qt*tx ;

			System.out.println(calculo.toString());
			
			String resultado = calculo.toString();
			this.r.setText(resultado);
		    
			
		}
			
}

	public JTextField getT1() {
		return t1;
	}

	public void setT1(JTextField t1) {
		this.t1 = t1;
	}

	public JTextField getT() {
		return t;
	}

	public void setT(JTextField t) {
		this.t = t;
	}

	public JTextField getR() {
		return r;
	}

	public void setR(JTextField r) {
		this.r = r;
	}

}

prog.tiago

Coloquei seu código dentro de code para facilitar a visualização. :wink:

package Frame;

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class ExemploFrame extends JFrame implements ActionListener

{ private JButton b1;
private JTextField t1;
private JTextField t;
private JTextField r;
private JFrame Janela;
private JLabel labelNome;
private JLabel labelNome1;
private JLabel labelNome2;


public static void main(String args[])

{
new ExemploFrame();


}

public ExemploFrame()
{

labelNome = new JLabel ("Quantidade: ");
labelNome.setLocation(10,10 );
labelNome.setSize(100, 30);

t = new JTextField();
t.setLocation(90, 10);
t.setSize(100, 30);

labelNome1 = new JLabel ("Taxa: ");
labelNome1.setLocation(10, 70);
labelNome1.setSize(100, 30);


t1 = new JTextField();
t1.setLocation(90, 70);
t1.setSize(100, 30);

labelNome2 = new JLabel ("Resultado: ");
labelNome2.setLocation(10,130 );
labelNome2.setSize(100, 30);

r = new JTextField();
r.setLocation(90, 130);
r.setSize(100, 30);


b1 = new JButton("Calcular");
b1.setLocation(10,190 );
b1.setSize(110, 30);
b1.addActionListener(this);

Janela = new JFrame();
Janela.setTitle("Digite os dados ");
Janela.setLayout(null);
Janela.add(t);
Janela.add(t1);
Janela.add(labelNome);
Janela.add(labelNome1);
Janela.add(labelNome2);
Janela.add(b1);
Janela.add(r);
Janela.setLocationRelativeTo(null);
Janela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Janela.setSize(300,300);
Janela.setVisible(true);
Janela.show();

}
public void actionPerformed(ActionEvent e)
{
if (e.getSource()== b1)

{
String quantidade = this.t.getText();

Double qt = Double.parseDouble(quantidade);

String taxa = this.t1.getText();
Double tx = Double.parseDouble(taxa);

Double calculo = qt*tx ;

System.out.println(calculo.toString());

String resultado = calculo.toString();
this.r.setText(resultado);


}

}

public JTextField getT1() {
return t1;
}

public void setT1(JTextField t1) {
this.t1 = t1;
}

public JTextField getT() {
return t;
}

public void setT(JTextField t) {
this.t = t;
}

public JTextField getR() {
return r;
}

public void setR(JTextField r) {
this.r = r;
}

}
prog.tiago

O que você quer que o método toString() imprima?

:?:

T

se for usar o System.out.println();

ele automaticamente já usa o método toString implicito

igual eu falei anteriormente

xxjamisxx

bem o que provalvelmente vc quer fazer
e pega um valor e retorna para para textField
valores numerico nao da para passa entao vc
tem que converte para string como nosso amigo
la em cima falo era mais facil vc usa o
String.valeuOf(numero)
mais ser vc quizer o toString ele
tambem converte para String

joaodaniel

Bom, você precisa reescrever o método toString.

Quando utilizamos o método toString em um double, ou em outro tipo já definido, esse método já foi escrito para imprimir exatamente o que você deseja. Isso é, transformar aquele objeto em uma String.

Quando criamos uma classe, ela extende Objeto, e herda o método toString da Classe Objeto. Porém essa implementação muitas vezes não é a que desejamos.
Experimente usar o método toString de uma classe que você criou, sem reescrevê-lo. Ele imprimirá a referência do objeto na memória.

O que fazemos então é reescrever o método toString para exibir o que desejamos. Por exemplo, se temos um classe Pessoa cujos atributos são nome e idade, uma opção é que o nosso método toString imprima esses atributos. Nesse caso faríamos:

@Override
public String toString() {
return "Nome: " + this.nome + ", Idade: " + this.idade;
}
Criado 3 de fevereiro de 2011
Ultima resposta 3 de fev. de 2011
Respostas 14
Participantes 8