Error in multiplication and division (java)

Asked

Viewed 335 times

2

I’m having trouble implementing multiplication and division in my calculator with graphical interface.

Regardless of anything I put using any of the operators (/ and *), the output result is 0.

Sum and subtraction are functioning normally.


package pkgCalculadora;

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

public class Calculadora extends JFrame implements ActionListener{

private JButton butSomar,butSubtrair, butMultiplicar, butDividir, butIgual;
private JButton but0,but1,but2,but3,but4,but5,but6,but7,but8,but9;
private JTextField campo1;
private JPanel painel1 = new JPanel();
private JPanel painel2 = new JPanel();
private JPanel painel3 = new JPanel();
private int leitura;
private int memoria;
private int op;

public Calculadora()
{
    super("Calculadora");        

    butSomar  = new JButton("+");     
    butSubtrair = new JButton(" -");
    butMultiplicar = new JButton("*");
    butDividir = new JButton(" /");
    butIgual = new JButton("=");

    but0 = new JButton("0");
    but1 = new JButton("1");
    but2 = new JButton("2");
    but3 = new JButton("3");
    but4 = new JButton("4");
    but5 = new JButton("5");
    but6 = new JButton("6");
    but7 = new JButton("7");
    but8 = new JButton("8");
    but9 = new JButton("9");

    campo1 = new JTextField(15);

    painel1.setLayout(new FlowLayout());
    painel2.setLayout(new BoxLayout(painel2, BoxLayout.Y_AXIS));
    painel3.setLayout(new FlowLayout());

    painel1.add(campo1);

    painel2.add(butSomar);
    painel2.add(butSubtrair);
    painel2.add(butMultiplicar);
    painel2.add(butDividir);
    painel2.add(butIgual);

    painel3.add(but0);
    painel3.add(but1);
    painel3.add(but2);
    painel3.add(but3);
    painel3.add(but4);
    painel3.add(but5);
    painel3.add(but6);
    painel3.add(but7);
    painel3.add(but8);
    painel3.add(but9);
    painel3.add(but0);

    butSomar.addActionListener(this);
    butSubtrair.addActionListener(this);
    butMultiplicar.addActionListener(this);
    butDividir.addActionListener(this);
    butIgual.addActionListener(this);

    but0.addActionListener(this);
    but1.addActionListener(this);
    but2.addActionListener(this);
    but3.addActionListener(this);
    but4.addActionListener(this);
    but5.addActionListener(this);
    but6.addActionListener(this);
    but7.addActionListener(this);
    but8.addActionListener(this);
    but9.addActionListener(this);


    add(painel1, BorderLayout.NORTH);
    add(painel2, BorderLayout.EAST);
    add(painel3, BorderLayout.CENTER);
 // certo

    // <HARD 1>

butSomar.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){     
    campo1.setText(campo1.getText() + "+");
    }
});

butSubtrair.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){     
    campo1.setText(campo1.getText() + "-");
    }
});

butMultiplicar.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){     
    campo1.setText(campo1.getText() + "*");
    }
});

butDividir.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){     
    campo1.setText(campo1.getText() + "/");
    }
});

but1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){   
    leitura += 1;
    campo1.setText(campo1.getText() + "1");
    }
});

but2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){   
    leitura += 2;
    campo1.setText(campo1.getText() + "2");
    }
});

but3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){     
    leitura += 3;
    campo1.setText(campo1.getText() + "3");
    }
});

but4.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){  
    leitura += 4;
    campo1.setText(campo1.getText() + "4");
    }
});

but5.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
    leitura += 5;
    campo1.setText(campo1.getText() + "5");
    }
});

but6.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
    leitura += 6;
    campo1.setText(campo1.getText() + "6");
    }
});

but7.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
    leitura += 7;
    campo1.setText(campo1.getText() + "7");
    }
});

but8.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
    leitura += 8;
    campo1.setText(campo1.getText() + "8");
    }
});

but9.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
    leitura += 9;
    campo1.setText(campo1.getText() + "9");
    }
});

but0.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
    leitura += 0;
    campo1.setText(campo1.getText() + "0");
    }
});

// </HARD 1>

// <HARD 2>

butSomar.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        op = '+';
        memoria += leitura; // guarda leitura na memoria
        leitura = 0;        // reseta memoria

    }
});

butSubtrair.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        op = '-';
        memoria -= leitura; 
        leitura = 0;        

    }
});

butMultiplicar.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        op = '*';
        memoria *= leitura; 
        leitura = 0;        

    }
});

butDividir.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        op = '/';
        memoria /= leitura; 
        leitura = 0;        

    }
});

butIgual.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        switch (op) {
            case '+': {
                memoria += leitura;
                break;
            }
            case '-': {
                memoria -= leitura;
                break;
            }
            case '*': {
                memoria *= leitura;
                break;
            }
            case '/': {
                memoria /= leitura;
                break;
            }
        }
        leitura = 0;
        campo1.setText("" + memoria);
    }
});

// </HARD 2>
}


public void actionPerformed(ActionEvent arg0) {
    // TODO Auto-generated method stub
}
}
  • In multiplication this is happening because you assign 0 to read and after that multiply it with memory. But I couldn’t identify why this happens to the division.

  • but reading naturally gets 0, because its value is passed to variable 'memory' .-.

  • Because you use int instead of double?

1 answer

5


Your problem is you’re never assigning memoria explicitly, only through operations with leitura. In addition this is not a problem, because:

  1. You type 2, the code makes leitura = 2; memoria is zero;
  2. You type +, the code makes memoria += leitura; memoria now is 2;
  3. You type 2, the code makes leitura = 2; memoria is 2;
  4. You type =, the code makes memoria += leitura; memoria now is 4.

In the others, it should be (you mentioned that the subtraction works, but according to your code it should not work...). For example, in the division:

  1. You type 2, the code makes leitura = 2; memoria is zero;
  2. You type /, the code makes memoria /= leitura; memoria is still zero;
  3. You type 2, the code makes leitura = 2; memoria is zero;
  4. You type =, the code makes memoria /= leitura; memoria still zero.

What you would need to do, in any of the four operations, would be something like:

butMultiplicar.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        op = '*';
        memoria = leitura; // Apenas atribua a "memoria" o valor de "leitura"
        leitura = 0;        
    }
});

But... this leads us to a second problem in your code: every time you enter with a digit, the value of the text field is being updated correctly, but the value of leitura nay:

  1. leitura is zero;
  2. You type 2, the code makes leitura += 2; leitura now is 2;
  3. You type 2, the code makes leitura += 2; leitura now is 4!

If you want to use operands with more than one digit, you need to multiply the current value by 10 before adding the next digit:

but2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){   
    leitura = leitura*10 + 2;
    campo1.setText(campo1.getText() + "2");
    }
});

Finally, a question: what if you enter with 2*2*2=? Only with the above changes, it would not be enough, as the second entry of * would overwrite memoria with 2 and the first 2* would be lost. The solution is to check - before assigning an operator - whether you already had another operator assigned there or not. If not, overwrite memoria; otherwise, perform the operation amid leitura, op and memoria:

private void calcular() {
    switch (op) {
        case '+':
            memoria + leitura;
            break;
        case '-':
            memoria -= leitura;
            break;
        case '*':
            memoria *= leitura;
            break;
        case '/':
            memoria /= leitura;
            break;
        case 0:
            memoria = leitura; // Nenhuma operação anterior, só atribua
    }
}

butMultiplicar.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        calcular();  // Atualiza memoria,
        op = '*';    // Coloca o novo operador
        leitura = 0; // E limpa leitura
    }
});

In addition to the four operators, the equal button can also use this function calcular, instead of repeating the logic:

butIgual.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        calcular();                   // Atualiza "memoria"
        campo1.setText("" + memoria); // Exibe seu valor
        leitura = memoria = op = 0;   // Limpa todos os dados
    }
});
  • His explanation was perfect, helped me even in mistakes that I had not seen. Thank you.

Browser other questions tagged

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