zoukankan      html  css  js  c++  java
  • 一段简单的手写Java计算器代码

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

    public class Calculator1 extends JFrame implements ActionListener {
    JTextField text;
    static boolean isFirst = true;
    double number = 0.0;
    public static String s = "0";
    double value,sum;
    int n;
    //主函数
    public static void main(String[] args){
    new Calculator1();
    }
    //构造方法
    public Calculator1(){
    JFrame mywindow = new JFrame();
    mywindow.setTitle("我的计算器V-1");
    mywindow.setSize(250,250);
    mywindow.setLocation(400,300);
    mywindow.setResizable(false);
    mywindow.setLayout(new BorderLayout());

    JPanel panel1 = new JPanel(new FlowLayout());
    JPanel panel2 = new JPanel(new GridLayout(4, 4));
    text = new JTextField("0",20);
    text.setEditable(false);
    panel1.add(text);
    mywindow.add("North", panel1);
    mywindow.add("Center", panel2);

    String[] array = {"7","8","9","C","4","5","6","+","1","2","3","-","0","*","/","="};
    JButton[] buttons = new JButton[array.length];
    for(int i=0;i<array.length;i++){
    buttons[i] = new JButton(array[i]);
    panel2.add(buttons[i]);
    }
    for(int i=0;i<buttons.length;i++){
    buttons[i].addActionListener(this);
    }
    mywindow.setVisible(true);
    }
    public void actionPerformed(ActionEvent e) {
    String oldstr = text.getText();
    String label = e.getActionCommand();
    if(label.equals("C")){
    s="0";

    value= 0;
    sum = 0;

    text.setText(s);
    }
    else if("+-*/=0123456789".indexOf(label) > 4){
    handNumber(label);
    }else{
    handOperator(label);
    }
    }
    //操作数字函数
    public void handNumber(String num){
    if(s.equals("0"))
    s = num;
    else
    s = s + num;
    text.setText(s);
    }
    //操作符号函数
    public void handOperator(String operator){
    value = Double.valueOf(s);
    switch(n)
    {
    case 0:sum = value;break;
    case 1:sum = sum + value;break;
    case 2:sum = sum - value;break;
    case 3:sum = sum * value;break;
    case 4:sum = sum / value;break;
    }
    if(operator.equals("=")){n = 0;}
    if(operator.equals("+")){n = 1;}
    if(operator.equals("-")){n = 2;}
    if(operator.equals("*")){n = 3;}
    if(operator.equals("/")){n = 4;}
    s = String.valueOf(sum);
    if(operator.equals("=")){
    text.setText(s);
    } else{
    text.setText(s+operator);
    s= "0";
    }


    }
    }

  • 相关阅读:
    定点数的表示
    [收集]XMPP使用tls 和sasl登录
    socket函数
    [收集] SendMessage、PostMessage原理
    DLL中用malloc分配了一块内存,但是在exe程序中释放引发的错误:其原因可能是堆被损坏,这也说明 **.exe 中或它所加载的任何 DLL 中有 bug。
    关于在IWebBrowser中无法响应Ctrl+C等快捷键的解决方法
    Enum 操作
    程序员面对分歧和难题应当具备的态度【转】
    NDIS学习笔记一
    NDIS学习笔记二——(模拟丢包)
  • 原文地址:https://www.cnblogs.com/wangxiuheng/p/4425474.html
Copyright © 2011-2022 走看看