Point function in calculator (broken numbers)

Asked

Viewed 4,938 times

5

I created a calculator with Swing and awt.Event, and I have three doubts !

First doubt: to create the calculator I used import with import.javax.swing. * and java.awt.Event. *, when I use *, am I using all the contents of the package that would come next to ""? because in some cases I have seen people using only javax.swing.jframe, and I wanted to know if * is to use all the classes that would come after it.

As last two doubts are similar, well, the whole calculator works perfectly with the exception of the button "." to add broken numbers (like 1.5 + 1.5) when I make an account with the button, it ignores the button and for example 1.5+1.5, instead of becoming 3, becomes 30, because it adds 15+15, you know ? In a forum I was told to do this:

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

public class Calculadora extends JFrame {
    private static final long serialVersionUID = 1L;

    private JButton n1;
    private JButton n2;
    private JButton n3;
    private JButton n4;
    private JButton n5;
    private JButton n6;
    private JButton n7;
    private JButton n8;
    private JButton n9;
    private JButton n0;
    private JButton botaoMais;
    private JButton botaoMenos;
    private JButton botaoVezes;
    private JButton botaoDividi;
    private JButton botaoIgual;
    private JButton botaoC;
    private JButton botaoCE;
    private JButton botaoPonto;
    private char operacao;
    private int inteiro;
    private int decimal;
    private double memoria;
    private boolean ponto;
    private JTextField campo;

    public Calculadora(){
        this.setTitle("Calculadora do Ozzy");
        this.setBounds(0,0,280,380);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.getContentPane().setLayout(null);

        inteiro = 0;
        decimal = 0;
        memoria = 0;

        n1 = new JButton ();
        n1.setText("1");
        n1.setBounds(25,115,45,45);
        this.add(n1);

        n2 = new JButton ();
        n2.setText("2");
        n2.setBounds(85,115,45,45);
        this.add(n2);

        n3 = new JButton();
        n3.setText("3");
        n3.setBounds(140,115,45,45);
        this.add(n3);

        n4 = new JButton();
        n4.setText ("4");
        n4.setBounds (25,170,45,45);
        this.add(n4);

        n5 = new JButton ();
        n5.setText("5");
        n5.setBounds(85,170,45,45);
        this.add (n5);

        n6 = new JButton();
        n6.setText("6");
        n6.setBounds(140,170,45,45);
        this.add(n6);

        n7 = new JButton ();
        n7.setText("7");
        n7.setBounds(25,225,45,45);
        this.add(n7);

        n8 = new JButton();
        n8.setText("8");
        n8.setBounds (85,225,45,45);
        this.add (n8);

        n9 = new JButton ();
        n9.setText("9");
        n9.setBounds (140,225,45,45);
        this.add (n9);

        n0 = new JButton();
        n0.setText ("0");
        n0.setBounds (140,280,45,45);
        this.add (n0);

        botaoMais = new JButton();
        botaoMais.setText("+");
        botaoMais.setBounds(195,115,45,45);
        this.add(botaoMais);

        botaoMenos = new JButton ();
        botaoMenos.setText ("-");
        botaoMenos.setBounds(195,170,45,45);
        this.add (botaoMenos);

        botaoVezes = new JButton();
        botaoVezes.setText ("x");
        botaoVezes.setBounds(195,225,45,45);
        this.add(botaoVezes);

        botaoDividi = new JButton();
        botaoDividi.setText("÷");
        botaoDividi.setBounds(195,280,45,45);
        this.add(botaoDividi);

        botaoIgual = new JButton();
        botaoIgual.setText("=");
        botaoIgual.setBounds(25,280,45,45);
        this.add(botaoIgual);

        botaoPonto = new JButton ();
        botaoPonto.setText(".");
        botaoPonto.setBounds(85,280,45,45);
        this.add (botaoPonto);

        botaoC = new JButton ();
        botaoC.setText("C");
        botaoC.setBounds(25,65,105,40);
        this.add(botaoC);

        botaoCE = new JButton ();
        botaoCE.setText("CE");
        botaoCE.setBounds(140,65,100,40);
        this.add(botaoCE);

        campo = new JTextField();
        campo.setBounds(25,25,216,30);
        this.add(campo);

        n1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                if(ponto){
                    decimal +=1;
                }
                inteiro *= 10;
                inteiro +=1;
                campo.setText(campo.getText()+ "1");

            }
        });
        n2.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                if (ponto){
                    decimal +=2;
                }
                inteiro *=10;
                inteiro+= 2;
                campo.setText (campo.getText()+"2");
            }
        });
        n3.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent event){
                if (ponto){
                    decimal+=3;
                }
                inteiro *= 10;
                inteiro += 3;
                campo.setText(campo.getText()+"3");

            }
        });
        n4.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                if (ponto){
                    decimal+=4;
                }
                inteiro *= 10;
                inteiro +=4;
                campo.setText (campo.getText ()+"4");

            }
        });
        n5.addActionListener(new ActionListener(){
            public void actionPerformed (ActionEvent evt){
                if (ponto){
                    decimal +=5;
                }
                inteiro*= 10;
                inteiro +=5;
                campo.setText (campo.getText ()+ "5");
            }
        });
        n6.addActionListener (new ActionListener (){
            public void actionPerformed (ActionEvent evt){
                if (ponto){
                    decimal +=6;
                }
                inteiro*= 10;
                inteiro +=6;
                campo.setText (campo.getText ()+ "6");
            }
        });
        n7.addActionListener(new ActionListener(){
            public void actionPerformed (ActionEvent evt){
                if(ponto){
                    decimal +=7;
                }
                inteiro*= 10;
                inteiro +=7;
                campo.setText (campo.getText()+"7");
            }
        });
        n8.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                if(ponto){
                    decimal +=8;
                }
                inteiro *=10;
                inteiro +=8;
                campo.setText(campo.getText()+"8");
            }
        });
        n9.addActionListener (new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                if (ponto){
                    decimal +=9;
                }
                inteiro *=10;
                inteiro +=9;
                campo.setText(campo.getText()+"9");

            }
        });
        n0.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                if(ponto){
                    decimal +=0;
                }
                inteiro*=10;
                inteiro +=0;
                campo.setText(campo.getText()+"0");
            }
        });
        botaoMais.addActionListener (new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                double numero =Double.parseDouble(String.format("%s.%s",inteiro,decimal));
                operacao = '+';
                if (memoria > 0){
                    memoria += numero;
                }else{
                        memoria = numero;
                    }
                inteiro = 0;
                numero = 0;
                decimal = 0;
                ponto = false;
                campo.setText("");
                }
            });
        botaoMenos.addActionListener (new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                double numero = Double.parseDouble (String.format("%s.%s",inteiro,decimal));
                operacao = '-';
                if (memoria > 0){
                    memoria -= numero;
                }else {
                    memoria = numero;
                }
                numero = 0;
                inteiro = 0;
                decimal = 0;
                ponto = false;
                campo.setText("");
            }
        });
        botaoVezes.addActionListener (new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                double numero = Double.parseDouble (String.format("%s.%s",inteiro,decimal));
                operacao = '*';
                if (memoria > 0){
                    memoria *= numero;
                }else {
                    memoria = numero;
                }
                numero = 0;
                inteiro =0;
                decimal =0;
                ponto = false;      
                campo.setText("");
            }
        });
        botaoDividi.addActionListener(new ActionListener(){
            public void actionPerformed (ActionEvent evt){
                double numero = Double.parseDouble(String.format("%s.%s",inteiro,decimal));
                operacao = '/';
                if(memoria >0){
                    memoria /=numero;
                }else {
                    memoria = numero;
                }
                numero=0;
                inteiro =0;
                decimal = 0;
                ponto = false;
                campo.setText("");
            }
        });
        botaoC.addActionListener (new ActionListener(){
            public void actionPerformed (ActionEvent evt){
                inteiro = 0;
                decimal = 0;
                memoria = 0;
                ponto = false;
                campo.setText("");
            }
        });
        botaoCE.addActionListener(new ActionListener(){
            public void actionPerformed (ActionEvent evt){
                inteiro = 0;
                decimal = 0;
                memoria = 0;
                ponto = false;
                campo.setText("");
            }
        });
        botaoPonto.addActionListener(new ActionListener(){
            public void actionPerformed (ActionEvent evt){
                if (!ponto){
                    campo.setText(inteiro +".");
                    ponto = (true);
                }
            }
        });
        botaoIgual.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                double numero = Double.parseDouble(String.format("%s.%s", inteiro, decimal));
                switch (operacao){
                case '+':{
                    memoria += numero;
                    break;
                }
                case '-':{
                    memoria -=numero;
                    break;
                }
                case '*':{
                    memoria *=numero;
                    break;
                }
                case '/':{
                    memoria /=numero;
                    break;
                }
                }
                numero = 0;
                campo.setText(""+ memoria);
            }
        });
    }

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

Reading is the variable double for the numbers I input into the calculator, and every time I entered with a number like 9, pressing the dot would turn into "9.0" and that would mess up the bill, but after that I put in (int), this ceased to occur.

I’m saying that in this field, on this button, and at this point, reading is no longer double to be int ? And how do I make my stitch work and stop being ignored like I said above ?

2 answers

3

About import has a booklet from Caelum that deals with it:

It is possible to "import an entire package" (all classes of the package except subpacks) via the joker *:

import java.util.*;

Importing all classes from a package does not imply a loss of performance at runtime, but can cause problems with classes of the same name! In addition, importing from one to one is considered good practice as it makes reading easier for other programmers. An IDE like Eclipse will already do that for you, as will the directory organization.

link to the booklet: http://www.caelum.com.br/apostila-java-orientacao-objetos/pacotes-organizando-suas-classes-e-libraries/#12-3-import

And about your problem with the numbers, I did something like this treating the digits added as String and when getting from the screen do a parse as follows:

    String str = "12.3";
    float f = Float.parseFloat(str);

if there are only 2 numbers to be added together maybe storing and converting two strings variables is enough, and then showing them on the screen and performing the calculations, but if you have more you can use an array of strings with some repetition structure, it is up to you.

  • I could not understand well man, but from what I understood, it did not work because my numbers are in double ! I haven’t been able to make it work yet, but I copied all the code here, if it helps you help me ! kk =]

1


When you do:

import javax.swing.*

It means that you will import all the classes in this package. There’s nothing wrong with that until you have class name conflicts, for example, if you want to use Date of java.util.Date and some class of the package java.sql, which in turn has a class java.sql.Date but that you don’t know of its existence. If you decided to do:

import java.util.Date;
import java.sql.*;

and then at some point in your code you use the class Date which of the two will be called?

Date d = new Date(); //java.util.Date ou java.sql.Date está sendo usada aqui?

In addition, writing the full name of the class being imported, i.e., package + class makes it easier to read the code later, because just by tapping the header one knows exactly which classes were imported.

Remember that if there is any other level within the package your classes will not be automatically imported.

EDITION

As his code was incomplete I made some assumptions that were not true, seeing now I could correctly identify the problems, come on:

You store it in a variable that will be counted every time you press a number or point (I would do it differently, but blz). So just like you do the dozens:

leitura *= 10;
leitura += 2; //supondo que apertou o botão dois

you must do the whole part separation for the decimal part.

From the moment you put a point, you will no longer do leitura *= 10, correct? Because the whole part has already been defined. The simplest way I could imagine to get out of this is for you to separate your variable leitura in two, one for that which is integer (that which is before the point) and another for that which is fraction (that which is after the point), would look like this:

private int inteiro;
private int decimal;
private double memoria;
private boolean ponto;

Realize that in addition to taking the leitura and put two variables in its place still added the variable ponto, which will serve when the dot button has been pressed and can separate that which is integer from that which is decimal:

botaoPonto.addActionListener(new ActionListener(){
    public void actionPerformed (ActionEvent evt){
        if(!ponto) { //olha que legal, não da mais para colocar mais de um ponto
            campo.setText(inteiro +".");
            ponto = true;
        }
    }
});
n1.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent evt){
        if(ponto) {
            decimal += 1;
        }
        else {
            inteiro *= 10;
            inteiro +=1;
        }
        campo.setText(campo.getText()+ "1");
    }
});

To sum you must compose a double number with the whole part and the decimal you read:

botaoMais.addActionListener (new ActionListener(){
    public void actionPerformed(ActionEvent evt){
        operacao = '+';
        //aqui é onde você compoe seu numero double
        double numero = Double.parseDouble(String.format("%s.%s", inteiro, decimal));
        if (memoria > 0){
            memoria += numero;
        }else{
            memoria = numero;
        }
        numero = 0;
        inteiro = 0;
        decimal= 0;
        ponto = false;
        campo.setText("");
    }
});

Inside your equal button you must make the same double number composition:

botaoIgual.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent evt){
        double numero = Double.parseDouble(String.format("%s.%s", inteiro, decimal));

And don’t forget to clear the point (set it false) when pressing CE or C.

Format()

The format() simulates the System.out.printf() which in turn was inspired by printf() of C.

It has the function of formatting a String according to the arguments passed. As the first argument is passed to String that will be edited together with placeholders, the other arguments are the values that will replace the String placeholders of the first argument. Example:

System.out.printf("A soma dos números é %s", 5 + 5);

Returns:

The sum of the numbers is 10

The result of the sum was put in place of the %s. It would also be possible to put %d, which is the placeholder for integer numbers (at base 10), however I treated them as strings.

A complete list of placeholders:

Symbol Description
%b Boolean
%c Character
%d Decimal integer (Signed)
%and Floating point number in Scientific format
%f Floating point numer in decimal format
%g Floating point numer in decimal or Scientific format (Depending on the value passed as argument)
%h Hashcode of the passed argument
%Line separator (new line Character)
%the Integer Formatted as an octal value
%s String
%t Date/time
%x Integer Formatted as an hexadecimal value

Reference: String - format() (Java Platform SE7)

  • I should add this command to the equal button ? I didn’t understand mt well, but I copied my entire code here, I hope it helps you help me ! If it’s not too easy to understand, let me know !

  • Who voted against could tell me where is wrong? Or reconsider the vote after the issue?

  • Good my friend, the program ran well, the Eclipse did not point out any error, however the same problem persists, the calculator is "ignoring" the point, but this time partially ! He is calculating what comes after the point, but at the same time he still reads the number as one, as if the point did not exist! as for example in an account like 1.50 + 1.50, the result of the 301.0 (makes 150 + 150, and still counts the .50, adding +1 !) I don’t understand how this is happening ! Any tips ? And thank you so much for your help so far, you’ve helped so much guy !

  • PS: if you can also explain to me the meaning of "%s. %s" I did not understand the meaning of it ! Thank you !

  • @Gabrielozzy basically missed a else inside your Actionlistener of each button referring to a number. I will add the detail of format in response.

  • Perfectly working, @Math, thank you so much man ! You’ve helped so much, I owe you a friend, thanks for helping a beginner ! Haha =]

Show 1 more comment

Browser other questions tagged

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