Calculadora

[code]
public class Calculadora extends javax.swing.JFrame {

double valor1 ,valor2, resultado;

int operacao;

/** Creates new form Calculadora */
public Calculadora() {
    initComponents();
}


private void b1ActionPerformed(java.awt.event.ActionEvent evt) {
   
tfsaida.setText(""+1);    

}

private void tfsaidaActionPerformed(java.awt.event.ActionEvent evt) {

}

private void b0ActionPerformed(java.awt.event.ActionEvent evt) {

tfsaida.setText(tfsaida.getText()+""+0);
}

private void b2ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    tfsaida.setText(""+2); 
}

private void b3ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    tfsaida.setText(""+3); 
}

private void b4ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    tfsaida.setText(""+4);

}

private void b5ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    tfsaida.setText(""+5); 
}

private void b6ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    tfsaida.setText(""+6); 
}

private void b7ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    tfsaida.setText(""+7); 
}

private void b8ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    tfsaida.setText(""+8); 
}

private void b9ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    tfsaida.setText(""+9); 
}

private void bsomaActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:

valor1=Double.parseDouble(tfsaida.getText());

tfsaida.setText("");

operacao=1;
}

private void bsubActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    valor1=Double.parseDouble(tfsaida.getText());

tfsaida.setText("");

operacao=2;
}

private void bmultActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    valor1=Double.parseDouble(tfsaida.getText());

tfsaida.setText("");

operacao=3;
}

private void bdivActionPerformed(java.awt.event.ActionEvent evt) {

valor1=Double.parseDouble(tfsaida.getText());

tfsaida.setText("");

operacao=4;
}

private void blimparActionPerformed(java.awt.event.ActionEvent evt) {

tfsaida.setText("");

}

private void bresultActionPerformed(java.awt.event.ActionEvent evt) {

{

valor2=Double.parseDouble(tfsaida.getText());

if(operacao==1)
{
resultado=valor1+valor2;
}
else if(operacao==2)
{
resultado=valor1-valor2;
}
else if(operacao==3)
{
resultado=valor1*valor2;
}
else if(operacao==4)
{
resultado=valor1/valor2;
}
tfsaida.setText(""+resultado);

}
}[/code]

Ai acontece o seguinte…
Quando digito do teclado, aparece o que eu digito. ex: 10+10+10… nao soma direto… tenho que clicar diretamente na calculadora
E quando faço na calculadora direto, funciona… porém o resutado sai… ex: clico 10+10… o resultado dá 20,0 … nao só 20.

sao esses pequenos probleminhas… rsrs…

alguem dá uma luz??

valeu :lol:

é pq o resultado retornado é um double. nesse caso vc pode utilizar o decimal format e ele removerá as casas decimais.

fazendo assim:


DecimalFormat decimalFormat = new DecimalFormat("0");

//e fazer assim

double resultado = 2.0;

System.out.println(decimalFormat.format(resultado)); // ele irá imprimir 2

caso queira com duas casas:


//com duas casas:
DecimalFormat decimalFormat = new DecimalFormat("0.00");

como eu adaptaria isso no meu codigo?

Amigo não verifiquei todo seu código mais ví que as variaveis foram declaradas como double.
Este é o motivo do retorno possuir casas dessimais. O amigo remixlara citou o DecimalFormat eficiente para ajustes de casas decimais em tipo double.
mais cuidado ao inserilo no seu código, ele pode te causar problemas relativos a aproximação de casas decimais:
EX: se voce dividir 7 por 2 o resultado correto é 3.5 (Não lembro como ele procede mais ele pode te retornar 4 caso arredonde o valor para cima, ou apenas 3 caso ignore tudo apos a virgula). Uma solução facil para isso é criar uma uma condição " if " para verificar se o retorno possue valor não nulo apos o ponto, se for 0 vc aplica o DecimalFormat(“0”), caso contrário retorna con a quantidade de casas decimais que vc quiser , DecimalFormat(“0.00”) como citado pelo remixlara.

package calculadora;

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

public class Calculadora extends JFrame implements ActionListener {

    private JButton somar, subtrair, multiplicar, dividir, limpar, voltar, igual, ponto;
    private JButton bt0, bt1, bt2, bt3, bt4, bt5, bt6, bt7, bt8, bt9;
    private JTextField tfVisor;
    private double n1, n2;
    private char operacao = ' ';
    private boolean segundo = true;
    private boolean utd = false;

    public Calculadora() {
        //Ajuste do formulário
        setTitle("Calculadora");
        setSize(245, 260);
        setLocation(WIDTH, WIDTH);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);
        getContentPane().setLayout(null);

        //Inicialização dos botões
        somar = new JButton("+");
        subtrair = new JButton("-");
        multiplicar = new JButton("*");
        dividir = new JButton("/");
        limpar = new JButton("CE");
        voltar = new JButton("Backspace");
        igual = new JButton("=");
        ponto = new JButton(",");
        bt0 = new JButton("0");
        bt1 = new JButton("1");
        bt2 = new JButton("2");
        bt3 = new JButton("3");
        bt4 = new JButton("4");
        bt5 = new JButton("5");
        bt6 = new JButton("6");
        bt7 = new JButton("7");
        bt8 = new JButton("8");
        bt9 = new JButton("9");
        tfVisor = new JTextField();

        //Posicionar componentes no formulário
        tfVisor.setBounds(10, 10, 220, 40);

        voltar.setBounds(10, 55, 160, 30);
        limpar.setBounds(180, 55, 50, 30);

        bt7.setBounds(10, 90, 50, 30);
        bt8.setBounds(65, 90, 50, 30);
        bt9.setBounds(120, 90, 50, 30);
        dividir.setBounds(180, 90, 50, 30);

        bt4.setBounds(10, 125, 50, 30);
        bt5.setBounds(65, 125, 50, 30);
        bt6.setBounds(120, 125, 50, 30);
        multiplicar.setBounds(180, 125, 50, 30);

        bt1.setBounds(10, 160, 50, 30);
        bt2.setBounds(65, 160, 50, 30);
        bt3.setBounds(120, 160, 50, 30);
        subtrair.setBounds(180, 160, 50, 30);

        bt0.setBounds(10, 195, 50, 30);
        ponto.setBounds(65, 195, 50, 30);
        igual.setBounds(120, 195, 50, 30);
        somar.setBounds(180, 195, 50, 30);

        //Cores dos componentes
        bt0.setForeground(Color.BLUE);
        bt1.setForeground(Color.BLUE);
        bt2.setForeground(Color.BLUE);
        bt3.setForeground(Color.BLUE);
        bt4.setForeground(Color.BLUE);
        bt5.setForeground(Color.BLUE);
        bt6.setForeground(Color.BLUE);
        bt7.setForeground(Color.BLUE);
        bt8.setForeground(Color.BLUE);
        bt9.setForeground(Color.BLUE);
        ponto.setForeground(Color.BLUE);

        somar.setForeground(Color.red);
        subtrair.setForeground(Color.red);
        multiplicar.setForeground(Color.red);
        dividir.setForeground(Color.red);
        igual.setForeground(Color.red);
        limpar.setForeground(Color.red);
        voltar.setForeground(Color.red);

        tfVisor.setHorizontalAlignment(JTextField.RIGHT);

        //Registro de componentes que executam ações

        bt0.addActionListener(this);
        bt1.addActionListener(this);
        bt2.addActionListener(this);
        bt3.addActionListener(this);
        bt4.addActionListener(this);
        bt5.addActionListener(this);
        bt6.addActionListener(this);
        bt7.addActionListener(this);
        bt8.addActionListener(this);
        bt9.addActionListener(this);
        somar.addActionListener(this);
        subtrair.addActionListener(this);
        multiplicar.addActionListener(this);
        dividir.addActionListener(this);
        igual.addActionListener(this);
        limpar.addActionListener(this);
        voltar.addActionListener(this);
        ponto.addActionListener(this);

        //Colocar os componentes no formulário
        this.getContentPane().add(somar);
        this.getContentPane().add(subtrair);
        this.getContentPane().add(multiplicar);
        this.getContentPane().add(dividir);
        this.getContentPane().add(tfVisor);
        this.getContentPane().add(bt0);
        this.getContentPane().add(bt1);
        this.getContentPane().add(bt2);
        this.getContentPane().add(bt3);
        this.getContentPane().add(bt4);
        this.getContentPane().add(bt5);
        this.getContentPane().add(bt6);
        this.getContentPane().add(bt7);
        this.getContentPane().add(bt8);
        this.getContentPane().add(bt9);
        this.getContentPane().add(igual);
        this.getContentPane().add(limpar);
        this.getContentPane().add(voltar);
        this.getContentPane().add(dividir);
        this.getContentPane().add(ponto);
    }

    public static void main(String args[]) {
        JFrame obj = new Calculadora();
        obj.setVisible(true);
    }

    public void actionPerformed(ActionEvent acao) {
        if (acao.getSource() == bt0) {
            if (tfVisor.getText().equals("")) {
                return;
            } else {
                numDigi("0");
            }
        } else if (acao.getSource() == bt1) {
            numDigi("1");
        } else if (acao.getSource() == bt2) {
            numDigi("2");
        } else if (acao.getSource() == bt3) {
            numDigi("3");
        } else if (acao.getSource() == bt4) {
            numDigi("4");
        } else if (acao.getSource() == bt5) {
            numDigi("5");
        } else if (acao.getSource() == bt6) {
            numDigi("6");
        } else if (acao.getSource() == bt7) {
            numDigi("7");
        } else if (acao.getSource() == bt8) {
            numDigi("8");
        } else if (acao.getSource() == bt9) {
            numDigi("9");
        } else if (acao.getSource() == ponto) {
            decimal();
        }
        if (acao.getSource() == limpar) {
            tfVisor.setText("");
            operacao = ' ';
            segundo = true;
            utd = false;
            n1 = 0;
            n2 = 0;
        }
        if (acao.getSource() == voltar) {
            int tam = tfVisor.getText().length();
            if (tam > 0) {
                tfVisor.setText(tfVisor.getText().substring(0, tam - 1));
            } else {
                return;
            }
        }
        if (acao.getSource() == somar) {
            igual();
            calcular('+');
        }
        if (acao.getSource() == subtrair) {
            igual();
            calcular('-');
        }
        if (acao.getSource() == multiplicar) {
            igual();
            calcular('*');
        }
        if (acao.getSource() == dividir) {
            igual();
            calcular('/');
        }
        if (acao.getSource() == igual) {
            igual();
        }
    }

    private void calcular(char c) {
        if (!tfVisor.getText().equals("")) {
            operacao = c;
            segundo = false;
            utd = false;
            n1 = Double.parseDouble(tfVisor.getText());
        } else {
            return;
        }
    }

    private void numDigi(String n) {
        if (segundo == true) {
            tfVisor.setText(tfVisor.getText() + n);
        } else {
            tfVisor.setText("");
            tfVisor.setText(tfVisor.getText() + n);
            segundo = true;
        }
    }

    private void igual() {
        if (operacao == '+') {
            n2 = n1 + Double.parseDouble(tfVisor.getText());
            tfVisor.setText("" + n2);
            n1 = 0;
            n2 = 0;
            operacao = ' ';
            segundo = false;
        } else if (operacao == '-') {
            n2 = n1 - Double.parseDouble(tfVisor.getText());
            tfVisor.setText("" + n2);
            n1 = 0;
            n2 = 0;
            operacao = ' ';
        } else if (operacao == '*') {
            n2 = n1 * Double.parseDouble(tfVisor.getText());
            tfVisor.setText("" + n2);
            n1 = 0;
            n2 = 0;
            operacao = ' ';
        } else if (operacao == '/') {
            n2 = n1 / Double.parseDouble(tfVisor.getText());
            tfVisor.setText("" + n2);
            n1 = 0;
            n2 = 0;
            operacao = ' ';
        } else {
            return;
        }
    }

    private void decimal() {
        if (utd == false) {
            if (tfVisor.getText().length() < 1) {
                numDigi("0.");
            }
            else if (possuePonto() == true){
                    return;
                }
                else{
                numDigi(".");
                }
            }
            utd = true;
        
    }

    private boolean possuePonto(){
        String v = tfVisor.getText();
        boolean b = false;
        for (int i = 0; i<v.length();i++){
            if (v.substring(i, i).equals(".")){
                b = true;
            }
            else {
                b = false;
            }
        }
        return b;
    }
}

Essa fiz com base na video aula do prof. Neri da Informaticom já tem algum tempo, procure por ele no youtube ou no site www.informaticon.com.br
se vc digitar no teclado tbm não funciona pq não foi implementado o key listener.
con serteza hà como melhorar este código, como disse antes gerei ele no inicio do meu estudo java e meo conhecimento em java era bem limitado.
agora já estou engatinhando.

Obs: se quiser só a calculadora implemente o método main
ou chame de qualquer aplicação.

Dê também uma lida no post:
Como acionar os botões de uma calculadora através do teclado