Point function in the calculator (broken numbers)

5

I've created a calculator with Swing and awt.event, and I have three questions!

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

The last two questions are similar, well, the whole calculator works perfectly except for 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 as it adds 15 + 15, you see? In a forum they told me 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 double variable for the numbers that I enter in the calculator, and every time I enter with a number like 9, pressing the dot turned "9.0" and it would disturb the account, but after I put int ), this has stopped happening.

I'm saying that in this field, in this button, and at that time, reading would stop being double to be int ? And how do I make my point work and stop being ignored as I said above?

    
asked by anonymous 14.04.2014 / 22:27

2 answers

1

When you do:

import javax.swing.*

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

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

Then at some point in your code you use the class Date which one is being called?

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

In addition, typing the full name of the class being imported, ie packet + class makes it easier to read the code later, just by hitting the header if you know exactly which classes were imported.

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

EDITION

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

You store in a variable that will be made the account every time you press a number or the point (I would do different, but blz). So, in the same way you do the dozen part:

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

You should do the separation from the whole part to the decimal part.

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

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

Note that in addition to taking leitura and putting two variables in its place I have still added the variable ponto , which will serve when the point button has been pressed and can separate what is integer from what 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 add you must compose a double number with the integer part and the decimal you have 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 should make the same composition as the double number:

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

And do not forget to clear the point (set it false ) when you press CE or C.

Format ()

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

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

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

Return:

  

The sum of the numbers is 10

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

A complete list of placeholders:

  

Symbol Description
  % b Boolean
  % c Character
  % d Decimal integer (signed)
  % e 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
  % n Line separator (new line character)
  % o Integer formatted as an octal value
  % s String
  % t Date / time
  % x Integer formatted as an hexadecimal value

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

    
14.04.2014 / 22:47
3

On the import you have a Caelum handout that deals with this:

  

You can "import an entire package" (all package classes except subpackages) through the wildcard *:

     

import java.util.*;

     

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

link to the handout:

And about your problem with the numbers, I did something like this by treating the digits added as String and at the time of getting the screen parse as follows:

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

If only 2 numbers to be added maybe store and convert two strings variables enough, and then show them on the screen and perform the calculations, but if you have more you can use an array of strings with some repetition structure , is at your discretion.

    
14.04.2014 / 22:48