Ứng dụng Calculator cực kì đơn giản cho các bạn mới học java

Discussion in 'Examples' started by vandung_tnvn, 25/6/12.

  1. vandung_tnvn New Member

    Hi vọng sẽ giúp 1 phần nhỏ cho các bạn mới học về java với gói awt:)

    Code:
    import java.awt.event.*;
    import java.awt.*;
    import java.applet.*;
    public class MyCalculator extends Applet{
        Button[] num=new Button[10];
        Button Clear=new Button("Clear");
        Button cong,tru,nhan,chia,bang,dot;
        TextArea tf;
        String hide;
        String dau;
        double x,y;
        boolean fd=true;
        public void init()
        {
    
            setLayout(new GridLayout(8,8));
            tf=new TextArea("",15,20);
    
            tf.setFont(new Font("arial",Font.BOLD,15));
            add(tf);
            Clear.addActionListener(new ActionListener()
                    {
     
                public void actionPerformed(ActionEvent e) {
                    tf.setText("");
                    fd=true;
                    hide="";
                }
    
                    });
            add(Clear);
            for(int i=0;i<10;i++)
            {
                num[i]=new Button(""+i);
                num[i].addActionListener(new AddText(i));
                num[i].setFont(new Font("Tahoma",Font.BOLD,18));
                num[i].setSize(10,10);
                add(num[i]);
            }
            dot=new Button(".");
            dot.addActionListener(new ActionListener()
            {
     
                public void actionPerformed(ActionEvent e) {
                    if(fd){
                  tf.setText(tf.getText()+".");
                  hide+=".";
                    fd=false;}
                }
    
            });
            dot.setFont(new Font("arial",Font.BOLD,18));
            add(dot);
            cong=new Button("+");
            cong.addActionListener(new BieuThuc("+"));
            cong.setFont(new Font("arial",Font.BOLD,18));
            tru=new Button("-");
            tru.addActionListener(new BieuThuc("-"));
            tru.setFont(new Font("arial",Font.BOLD,18));
            nhan=new Button("*");
            nhan.addActionListener(new BieuThuc("*"));
            nhan.setFont(new Font("arial",Font.BOLD,18));
            chia=new Button("/");
            chia.addActionListener(new BieuThuc("/"));
            chia.setFont(new Font("arial",Font.BOLD,18));
            bang=new Button("=");
            bang.addActionListener(new Bang());
            bang.setFont(new Font("arial",Font.BOLD,18));
            add(cong);
            add(tru);
            add(nhan);
            add(chia);
            add(bang);
        }
        class AddText implements ActionListener
    {
    
        int i;
     
        AddText(int i)
        {
    
            this.i=i;
     
        }
    
        public void actionPerformed(ActionEvent e) {
    
            tf.setText(tf.getText()+i);
            hide+=i;
    
        }
    }
    class BieuThuc implements ActionListener
    {
        String DAU;
        BieuThuc(String d)
        {
            DAU=d;
    
        }
     
        public void actionPerformed(ActionEvent e) {
            dau=DAU;
          x=Double.parseDouble(tf.getText());
          hide="";
          tf.setText(tf.getText()+dau);
          fd=true;
        }
    
    }
    class Bang implements ActionListener
    {
      
        public void actionPerformed(ActionEvent e) {
            double kq = 0;
     
            y=Double.parseDouble(hide);
            if(dau=="+")
            {
                kq=x+y;
    
            }
            if(dau=="-")
            {
                kq=x-y;
    
            }
            if(dau=="*")
            {
                kq=x*y;
    
            }
            if(dau=="/")
            {
                kq=x/y;
    
            }
            tf.setText(tf.getText()+"="+kq);
        }
    
    }
    }
    
    SITUVN, vspro, quanlu and 2 others like this.
  2. JackV Administrator

    Thêm ghi chú cho code và tấm hình minh họa nhé bạn.
  3. vandung_tnvn New Member

    Hj. Ok. Mình đang phát triển ứng dụng để tính biểu thức có nhiều toán tử hơn:)
  4. vandung_tnvn New Member

    Sau 1 ngày mình đã phát triển tiếp ứng dụng để có thể tính toán nhiều phép tính trên 1 biểu thức, ai quan tâm thì pm để mình share nhé!
    [IMG]
    leocean likes this.
  5. mr.trung91 New Member

    Share mình với
  6. TamGa New Member

  7. vandung_tnvn New Member

    Ok.
    Nhưng hiện giờ
    mình ko có mạng.
    Để thứ 2 tuần sau
    mình share cho bạn
    nhé:)
  8. leocean New Member

  9. tienthanhk16 New Member

  10. Dinh Duy Trong New Member

  11. JackV Administrator

    Ay da, share thì share đi, email nữa cho nhộn nhịp đây mà
  12. congkt New Member

  13. vandung_tnvn New Member

    Vô cùng xin lỗi các bạn vì lâu mình ko lên đây nên ko biết các bạn xin code nhiều như vậy. Mình sẽ share cho các bạn code cho các bạn nhanh nhất có thể. Mong các bạn thông cảm!
  14. vandung_tnvn New Member

    Mình đã gửi mail cho tất cả các bạn rùi đấy. Code của nó đây:
    Code:
    import java.awt.event.*;
    import java.awt.*;
    import java.applet.*;
    public class MayTinh extends Applet{
        Panel p1,p2;
        Button[] num=new Button[10];
        Button Clear=new Button("Clear");
        Button cong,tru,nhan,chia,bang,dot,mu;
        Button sin,cos,tan,ln,log,canb2,gt;
        Button pi,e;
        TextArea tf;
        String[] number=new String[20];
        String[] dau=new String[20];
        int dem;
        Double[] x=new Double[20];
        boolean fd=true,kt=true, fham,fc,fgt;
        String ham,hang;
        Label info;
        public void init()
        {
            p1=new Panel();
            p2=new Panel();
            setLayout(new BorderLayout());
            initArray();
            tf=new TextArea(1,30);
            tf.setFont(new Font("ARIAL",Font.BOLD,18));
            tf.setEditable(false);
            p1.add(tf);
            p1.setLayout(new FlowLayout(FlowLayout.CENTER));
            add("North",p1);
            Clear.addActionListener(new ActionListener()
                    {
     
                public void actionPerformed(ActionEvent e) {
                    tf.setText("");
                    fd=true;
                    initArray();
    
                }
    
                    });
            Clear.setFont(new Font("ARIAL",Font.BOLD,18));
            p2.add(Clear);
            for(int i=0;i<10;i++)
            {
                num[i]=new Button(""+i);
                num[i].addActionListener(new AddText(i));
                num[i].setFont(new Font("Comic Sans MS",Font.BOLD,18));
                p2.add(num[i]);
            }
            dot=new Button(".");
            dot.setFont(new Font("Comic Sans MS",Font.BOLD,18));
            dot.addActionListener(new ActionListener()
            {
     
                public void actionPerformed(ActionEvent e) {
                    if(fd){
                  tf.setText(tf.getText()+".");
                  number[dem]+=".";
                    fd=false;}
                }
    
            });
            p2.add(dot);
            cong=new Button("+");
            cong.setFont(new Font("Comic Sans MS",Font.BOLD,18));
            cong.addActionListener(new BieuThuc("+"));
            tru=new Button("-");
            tru.setFont(new Font("Comic Sans MS",Font.BOLD,18));
            tru.addActionListener(new BieuThuc("-"));
            nhan=new Button("*");
            nhan.setFont(new Font("Comic Sans MS",Font.BOLD,18));
            nhan.addActionListener(new BieuThuc("*"));
            chia=new Button("/");
            chia.setFont(new Font("Comic Sans MS",Font.BOLD,18));
            chia.addActionListener(new BieuThuc("/"));
            bang=new Button("=");
            bang.setFont(new Font("Comic Sans MS",Font.BOLD,18));
            bang.addActionListener(new Bang());
            sin=new Button("sin");
            sin.setFont(new Font("Comic Sans MS",Font.BOLD,18));
            sin.addActionListener(new Ham("sin"));
            cos=new Button("cos");
            cos.setFont(new Font("Comic Sans MS",Font.BOLD,18));
            cos.addActionListener(new Ham("cos"));
            tan=new Button("tan");
            tan.setFont(new Font("Comic Sans MS",Font.BOLD,18));
            tan.addActionListener(new Ham("tan"));
            ln=new Button("ln");
            ln.setFont(new Font("Comic Sans MS",Font.BOLD,18));
            ln.addActionListener(new Ham("ln"));
            log=new Button("log");
            log.setFont(new Font("Comic Sans MS",Font.BOLD,18));
            log.addActionListener(new Ham("log"));
            canb2=new Button("√");
            canb2.setFont(new Font("Comic Sans MS",Font.BOLD,18));
            canb2.addActionListener(new Ham("√"));
            mu=new Button("^");
            mu.setFont(new Font("Comic Sans MS",Font.BOLD,18));
            mu.addActionListener(new BieuThuc("^"));
            pi=new Button("π");
            pi.setFont(new Font("Comic Sans MS",Font.BOLD,18));
            pi.addActionListener(new Hang("π"));
            e=new Button("e");
            e.setFont(new Font("Comic Sans MS",Font.BOLD,18));
            e.addActionListener(new Hang("e"));
            gt=new Button("!");
            gt.setFont(new Font("Comic Sans MS",Font.BOLD,18));
            gt.addActionListener(new GiaiThua());
            p2.add(cong);
            p2.add(tru);
            p2.add(nhan);
            p2.add(chia);
            p2.add(bang);
            p2.add(sin);
            p2.add(cos);
            p2.add(tan);
            p2.add(ln);
            p2.add(log);
            p2.add(canb2);
            p2.add(mu);
            p2.add(pi);
            p2.add(e);
            p2.add(gt);
            p2.setLayout(new GridLayout(9,3,5,5));
            add("Center",p2);
            info=new Label("Develop by VDungBK",Label.CENTER);
            info.setFont(new Font("Arial Unicode MS",Font.ITALIC,16));
            add("South",info);
        }
        class AddText implements ActionListener
    {
        int i;
        AddText(int i)
        {
            this.i=i;
        }
        public void actionPerformed(ActionEvent e) {
            tf.setText(tf.getText()+i);
            number[dem]+=i;
        }
    }
    class BieuThuc implements ActionListener
    {
        String DAU;
        BieuThuc(String d)
        {
            DAU=d;
        }
    
        public void actionPerformed(ActionEvent e) {
          dau[dem]=DAU;
          if(fham)
          {
              if(fc)
          {
              if(hang=="π") x[dem]=new Double(Math.PI);
              if(hang=="e")  x[dem]=new Double(Math.E);
              fc=false;
          }
          else if(fgt)
              {
                  x[dem]=new Double(giaithua(Double.parseDouble(number[dem])));
                  fgt=false;
              }
              else x[dem]=new Double(number[dem]);
              x[dem]=new Double(TinhToan(x[dem].doubleValue(),ham));
                tf.setText(tf.getText()+")"+dau[dem]);
                fham=false;
          }
          else
          {
              if(fc)
          {
              if(hang=="π") x[dem]=new Double(Math.PI);
              if(hang=="e")  x[dem]=new Double(Math.E);
              fc=false;
          }
              else if(fgt)
              {
                  x[dem]=new Double(giaithua(Double.parseDouble(number[dem])));
                  fgt=false;
              }
            else  x[dem]=new Double(number[dem]);
          tf.setText(tf.getText()+dau[dem]);}
          fd=true;
          dem++;
    
        }
    }
    class Bang implements ActionListener
    {
        public void actionPerformed(ActionEvent e) {
            if(fham)
          {
              if(fc)
          {
              if(hang=="π") x[dem]=new Double(Math.PI);
              if(hang=="e")  x[dem]=new Double(Math.E);
              fc=false;
          }
          else if(fgt)
              {
                  x[dem]=new Double(giaithua(Double.parseDouble(number[dem])));
                  fgt=false;
              }
              else x[dem]=new Double(number[dem]);
              x[dem]=new Double(TinhToan(x[dem].doubleValue(),ham));
                tf.setText(tf.getText()+")");
                fham=false;
          }
          else {
                if(fc)
          {
              if(hang=="π") x[dem]=new Double(Math.PI);
              if(hang=="e")  x[dem]=new Double(Math.E);
              fc=false;
          }
              else if(fgt)
              {
                  x[dem]=new Double(giaithua(Double.parseDouble(number[dem])));
                  fgt=false;
              }
            else  x[dem]=new Double(number[dem]);
            }
            for(int i=0;i<=dem;i++)
            {
                if(dau[i]=="^")
                        {
                            x[i]=new Double(TinhToan(x[i].doubleValue(),x[i+1].doubleValue(),dau[i]));
                            Tut(i);
                            i--;
                            dem--;
                        }
            }
            for(int i=0;i<=dem;i++)
            {
                if(dau[i]=="*"||dau[i]=="/")
                        {
                            x[i]=new Double(TinhToan(x[i].doubleValue(),x[i+1].doubleValue(),dau[i]));
                            Tut(i);
                            i--;
                            dem--;
                        }
            }
          for(int i=0;dem>0;i++)
            {
                if(dau[i]=="+"||dau[i]=="-")
                        {
                            x[i]=new Double(TinhToan(x[i].doubleValue(),x[i+1].doubleValue(),dau[i]));
                            Tut(i);
                            i--;
                            dem--;
                        }
    
            }
          tf.setText(tf.getText()+"="+x[0].toString());
        }
    }
    public double TinhToan(double x1,double x2,String d)
    {
        if(d=="+") return(x1+x2);
        else if(d=="-") return(x1-x2);
        else if(d=="*") return(x1*x2);
        else if(d=="^") return Math.pow(x1, x2);
        else return(x1/x2);
    }
    public double TinhToan(double x,String d)
    {
        if(d=="sin") return Math.sin(Math.toRadians(x));
        if(d=="cos") return Math.cos(Math.toRadians(x));
        if(d=="tan") return Math.tan(Math.toRadians(x));
        if(d=="ln")  return Math.log(x);
        if(d=="log") return Math.log10(x);
        if(d=="√")  return Math.sqrt(x);
        else return 0;
    }
    public void Tut(int i)
    {
        for(int j=i;j<=dem;j++)
        {
            x[j+1]=x[j+2];
            dau[j]=dau[j+1];
        }
    }
    public void initArray()
    {
        for(int i=0;i<20;i++)
            {
                number[i]="0";
                dau[i]="+";
                dem=0;
                x[dem]=new Double(0);
                fc=false;
                fgt=false;
            }
    }
    class Ham implements ActionListener
    {
        String D;
        Ham(String d)
        {
            D=d;
        }
            public void actionPerformed(ActionEvent e)
            {
              ham=D;
              fham=true;
              tf.setText(tf.getText()+ham+"(");
            }
    
    }
    class Hang implements ActionListener
    {
        String c;
        Hang(String c)
        {
            this.c=c;
        }
            public void actionPerformed(ActionEvent e)
            {
                hang=c;
                tf.setText(tf.getText()+hang);
                fc=true;
            }
    }
    class GiaiThua implements ActionListener
    {
            public void actionPerformed(ActionEvent e)
            {
                fgt=true;
                tf.setText(tf.getText()+"!");
            }
    
    }
    public int giaithua(double x)
    {
        int kq=1;
        int n=(new Double(x)).intValue();
        if(n==0) return 1;
        else for(int i=1;i<=n;i++)
        {
            kq*=i;
        }
        return kq;
    }
    }
    
  15. January New Member

    Bác chia sẻ cho em cái thuật toán tính toán biểu thức được không ạ
    vd 1+2*3+5454-432 chẳng hạn
    làm sao tính được biểu thức này ạ ..
    tks bác.
  16. vandung_tnvn New Member

    cái code mình vừa post tính đc như thế đấy bạn ạ:)
    nick4ever likes this.
  17. vspro New Member

    Thank pro, đang cần gấp.
  18. thanhlikes09bkdn Active Member

    Bó chân thằng Sinh =))
  19. thanhlikes09bkdn Active Member

    Đây là bài mình tự làm.
    Cũng thi xong rồi! Thành tích không được như ý muốn:mad:. Share cho ai cần!
    Xử lý các chức năng cơ bản trong win. Còn một số cái khiếm khuyết các bác tự thêm điều kiện :D
    Giao diện em nó:
    [IMG]
    Code:
    //============================================================================
    // Name        : Gui.java
    // Author      : thanhlikes09
    // Version    :
    // Copyright  : Your copyright notice
    // Description : Hello World in Java, Ansi-style
    // Date    Create : Jan 4, 2013
    //============================================================================
    
    package calculate;
    
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.HeadlessException;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    
    public class Gui extends JFrame implements ActionListener {
    
        private GridBagConstraints gridBagConstraints;
        private GridBagLayout gridBagLayout;
        private JPanel pn;
        private JTextField tf;
        private JButton[] bt;
        private String strBt = "0123456789+-*/.CB=";
        private char operator;
        private boolean isN2 = false;
        private boolean isEqual;
        private double n1 = 0, n2 = 0, result = 0;
    
        public Gui() throws HeadlessException {
            super();
            // TODO Auto-generated constructor stub
    
            setSize(215, 155);
            setLocationRelativeTo(null);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            gridBagConstraints = new GridBagConstraints();
            setResizable(false);
            gridBagLayout = new GridBagLayout();
            pn = new JPanel(gridBagLayout);
            bt = new JButton[strBt.length()];
            for (int i = 0; i < bt.length - 1; i++) {
                bt[i] = new JButton("" + strBt.charAt(i));
                addComponent(bt[i], i / 5, i % 5, 1, 1);
                bt[i].addActionListener(this);
            }
            int i = bt.length - 1;
    
            bt[i] = new JButton("" + strBt.charAt(i));
            addComponent(bt[i], i / 5, i % 5, 1, 3);
            bt[i].addActionListener(this);
    
            tf = new JTextField("0");
            tf.setHorizontalAlignment(JTextField.RIGHT);
            tf.setEditable(false);
            add(tf, BorderLayout.NORTH);
            add(pn);
            setVisible(true);
        }
    
        private void addComponent(Component c, int row, int col, int nrow, int ncol) {
            gridBagConstraints.fill = GridBagConstraints.BOTH;
            gridBagConstraints.gridx = col;
            gridBagConstraints.gridy = row;
            gridBagConstraints.gridheight = nrow;
            gridBagConstraints.gridwidth = ncol;
            gridBagLayout.setConstraints(c, gridBagConstraints);
            pn.add(c);
        }
    
        public static void main(String[] args) {
            new Gui();
        }
    
        /*
        * (non-Javadoc)
        *
        * @see
        * java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
        */
        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
    
            for (int i = 0; i < 10; i++) {
    
                if (e.getSource() == bt[i]) {
                    isEqual = false;
                    addNumber(i);
                    break;
                }
            }
            for (int i = 10; i < 14; i++) {
                if (e.getSource() == bt[i]) {
                    isEqual = false;
                    n1 = Double.parseDouble(tf.getText());
                    isN2 = true;
                    operator = bt[i].getText().charAt(0);
                }
    
            }
            // .
            if (e.getSource() == bt[14]) {
                isEqual = false;
                if (tf.getText().indexOf(".") == -1) {
                    tf.setText(tf.getText() + ".");
                }
            }
            // C
            if (e.getSource() == bt[15]) {
                clear();
            }
            // B
            if (e.getSource() == bt[16]) {
                isEqual = false;
                backSpace();
            }
            // =
            if (e.getSource() == bt[17]) {
                if (isEqual == false)
                    n2 = Double.parseDouble(tf.getText());
                else {
                    n1 = result;
    
                }
                setOperator(operator);
                isEqual = true;
            }
        }
    
        private void setOperator(char operator) {
            switch (operator) {
            case '+':
                result = n1 + n2;
    
                break;
            case '-':
                result = n1 - n2;
    
                break;
            case '*':
                result = n1 * n2;
    
                break;
            case '/':
                result = n1 / n2;
    
                break;
    
            }
            String strResult = Double.toString(result);
            if (result - Math.floor(result) == 0) {
                tf.setText(strResult.substring(0, strResult.length() - 2));
            } else
                tf.setText(Double.toString(result));
        }
    
        private void clear() {
            tf.setText("0");
            result = 0;
            n1 = 0;
            n2 = 0;
            isEqual = false;
            isN2 = false;
    
        }
    
        private void backSpace() {
            tf.setText(tf.getText().substring(0, tf.getText().length() - 1));
            if (tf.getText().isEmpty()) {
                tf.setText("0");
            }
        }
    
        private void addNumber(int i) {
            if (Double.parseDouble(tf.getText()) == 0f) {
                tf.setText("");
            }
            if (isN2 == true) {
                isN2 = false;
                tf.setText("");
            }
            tf.setText(tf.getText() + i);
        }
    }
    
    SITUVN likes this.

Chia sẻ trang này



Ve may bay di Ha Noi | Ve may bay di Vinh | Ve may bay di Hue | Ve may bay di Da Nang | Ve may bay di Nha Trang | Ve may bay di Da Lat | Ve may bay di Phu Quoc | Ve may bay di Sai Gon | Ve may bay di TPHCM | Ve may bay di Buon Me Thuot | Ve may bay di Hai Phong | Ve may bay di Dong Hoi | Ve may bay Vietjet Air | Phong ve may bay Vietjet Air | Ve may bay Vietnam Airlines | Phong ve may bay Vietnam Airlines | Ve may bay Vietnam Airlines | Ve may bay gia re | Ve may bay | Mua ve may bay | Jetstar | Vietnam Airlines | Air Asia | Tiger Airways | Ve may bay di My | Vietjet Air | Ve may bay di Ha Noi | Ve may bay di Da Nang | Ve may bay di Hai Phong | Ve may bay di Vinh