java实现简单计算器

界面:

若存在Bug,概不负责,请谨慎使用(^-^)。正常使用没问题,还有些功能在修复...

仅供参考!

参考了一些:

https://blog.csdn.net/lsq_401/article/details/79678187

https://blog.csdn.net/z8110/article/details/52734783

源代码:

package lianxi;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Queue;
import java.util.Stack;
import java.util.Vector;
import javax.swing.*;
import java.util.EventObject.*;
import java.io.*;
import java.math.BigDecimal;

public class Caculator extends JFrame {
    String input = "";
    String cs = " ";
    JTextField tf = new JTextField();
    JTextArea text = new JTextArea();
    JPanel panel1 = new JPanel();
    JPanel contentPane = new JPanel();
    StringBuffer strBuf = new StringBuffer();
    JButton[] jbs = new JButton[20];
    JButton save = new JButton("保存");
    JButton copy = new JButton("复制");
    JButton clear = new JButton("清除");
    JScrollPane js = new JScrollPane(text);// 滚动条
    public Caculator() {
        JFrame frame = new JFrame("计算器");           // 窗框
        tf.setHorizontalAlignment(JTextField.RIGHT);// 右对齐
        // tf.setEditable(false);//文本框禁止编辑
        tf.setBounds(0, 10, 350, 20);       
        js.setBounds(360, 5, 200, 70);
        panel1.setLayout(new GridLayout(4, 5, 0, 0));
        panel1.setBounds(0, 30, 350, 80);
        save.setBounds(360, 80, 60, 30);
        copy.setBounds(430, 80, 60, 30);
        clear.setBounds(500, 80, 60, 30);
        contentPane.setLayout(null);
        contentPane.add(tf);
        contentPane.add(panel1);
        contentPane.add(js);    
        contentPane.add(save);
        contentPane.add(copy);
        contentPane.add(clear);
        frame.setContentPane(contentPane);

        ArrayList<String> strArray = new ArrayList<String>();
        strArray.add("1");  strArray.add("2");
        strArray.add("3");  strArray.add("+");
        strArray.add("c");  strArray.add("4");
        strArray.add("5");  strArray.add("6");
        strArray.add("-");  strArray.add("退格"); 
        strArray.add("7");  strArray.add("8");
        strArray.add("9");  strArray.add("*");
        strArray.add("√");strArray.add("0");
        strArray.add(".");strArray.add("%");
        strArray.add("/");  strArray.add("=");

        for (int i = 0; i < jbs.length; i++) {
            jbs[i] = new JButton(strArray.get(i) + "");
            jbs[i].setSize(70, 30);
            panel1.add(jbs[i]);
            jbs[i].addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent arg0) {
                    // TODO Auto-generated method stub
                    String s = arg0.getActionCommand();
                    if (s.equals("=") == false) {// 不为等于时全显示
                        cs += s;
                    }
                    if (s.equals("c")) {
                        cs = " ";
                        input = "";
                    }
                    if (s.equals("退格")) {
                        int m = input.length();
                        int flag = 0;
                        for (int i = 0; i < cs.length(); i++) {
                            if (tf.getText().equals("") && cs.charAt(i) == '退') {
                                flag = 1;
                                cs = " ";
                                return;
                            }
                        }
                        if (flag == 0) {
                            if (m == 1) {
                                input = input.substring(0, 0);// 防止输入一个数字就退格
                                tf.setText("");
                                return;
                            }
                            if (input.charAt(m - 2) == '+' || input.charAt(m - 2) == '-' || input.charAt(m - 2) == '*'
                                    || input.charAt(m - 2) == '/' || input.charAt(m - 2) == '%' || input.charAt(m - 2) == '√') {
                                input = input.substring(0, input.length() - 3);
                            } else
                                input = input.substring(0, input.length() - 1);
                            cs = cs.substring(0, cs.length() - 3);
                        }
                    }
                    tf.setText(cs);
                    if (s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/") || s.equals("%")|| s.equals("√")) {
                        input += " " + s + " ";
                    } else if (s.equals("=")) {
                        String input1 = "";
                        String show = "";
                        for (int i = 0; i < input.length(); i++) {
                            if (input.charAt(i) != 'c') {
                                input1 += input.charAt(i);
                            }
                        }
                        show = input1 + "=" + " " + compute(input);
                        strBuf.append(show + "\n");
                        text.setText(strBuf.toString());
                    } else if (s.equals("退格") == false) {
                        /*这里如果改成if (s.equals("退格") == false||s.equals("c") == false)
                         的话,那么当输入"c"时逻辑判断第一个成立,逻辑短路,条件成立。那么就将"c"假如到了input
                        因此,在compute计算函数中才将"c"取出*/
                        input += s;
                    }
                }
            });
            save.addActionListener(new ActionListener() { // 按钮动作事件处理
                public void actionPerformed(ActionEvent e) {
                    BufferedWriter out = null;
                    int flag=0;
                    File file = new File("d://writeFile.txt");

                    try {
                        out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
                        out.append(text.getText());
                        out.write(123);
                    } catch (Exception e0) {
                        e0.printStackTrace();
                    } finally {
                        try {
                            out.flush();
                            out.close();
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                    }
                }

            });
            copy.addActionListener(new ActionListener() { // 按钮动作事件处理
                public void actionPerformed(ActionEvent e) {
                    text.copy();//这个没用
                }
            });
            clear.addActionListener(new ActionListener() { // 按钮动作事件处理
                public void actionPerformed(ActionEvent e) {
                    text.setText("");
                    strBuf.setLength(0); // 清空strBuf中的数据
                }
            });
        }
        frame.setBounds(100, 200, 600, 150);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setResizable(false);// 窗口大小不可改变
    }

    public static void main(String[] args) {// static
        new Caculator();
    }
    public static int sq(int n){//求根号时先求整数
        if( n == 1){
            return 1;
        }
        int tmp = 0;
        for(int i=1;i<=n/2+1;i++){
            if(i*i == n){
                tmp = i;
                break;
            }
            if(i*i > n){
                tmp = i-1;
                break;
            }
        }
        return tmp;
    }
    public static double[] sc(int m){   //m==3保留三位小数
        double[] arr = new double[m];
        int num = 0;
        while(num != m){
            double f = 1;
            for(int i=0;i<=num;i++){
                f = f*10;
            }
            arr[num] = 1/f;//arr[0]=0.1 f==10、arr[1]=0.01 f==100、arr[2]=0.001 f==1000
            num++;
        }
        return arr;
    }
    public static double sb(int n, double j, double[] arr){
        double tmp = j;                     
        for(int p=0;p<arr.length;p++){
            if(p>0){
                j = tmp;//计算过后的值(整数位+小数位的和,赋值给j,下面继续运算)
            }
            for(int i=1;i<=9;i++){//小数位只有九位{0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9}
                tmp = i*arr[p]+j;
                if(tmp*tmp == n){
                    return tmp;
                }
                if(tmp*tmp >n){
                    //避免丢失精度
                    BigDecimal c1 = new BigDecimal(Double.toString(tmp));
                    BigDecimal c2 = new BigDecimal(Double.toString(arr[p]));
                    tmp = c1.subtract(c2).doubleValue();
                    break;
                }
            }
        }
        return tmp;
    }
    private String compute(String input)// 即1237 的 样例
    {
        String str[];
        String inputnew = "";
        double dou;
        for (int i = 0; i < input.length(); i++) {
            if (input.charAt(i) != 'c') {
                inputnew += input.charAt(i);
            }
        }
        str = inputnew.split(" ");// 以空格分隔
        if (str[1].compareTo("√") == 0) {
            String str1="";
            for(int j=2;j<str.length;j++) {
                str1+=str[j];
            }
            double ans1 = Double.parseDouble(str1);//这里转化一下
            if(ans1==0) return "false";
            if(ans1==1) return String.valueOf(ans1);
            dou=sb((int)ans1,sq((int)ans1), sc(3));
            String result1 = String.valueOf(dou);
            return result1;
        }
        //1+2+3
        Stack<Double> s = new Stack<Double>();
        double m = Double.parseDouble(str[0]);//第一个为数字,奇数为运算符,偶数为操作数
        s.push(m);
        for (int i = 1; i < str.length; i++) {
            if (i % 2 == 1) {
                if (str[i].compareTo("+") == 0) {
                    double help = Double.parseDouble(str[i + 1]);
                    s.push(help);
                }

                if (str[i].compareTo("-") == 0) {
                    double help = Double.parseDouble(str[i + 1]);
                    s.push(-help);
                }

                if (str[i].compareTo("*") == 0) {//1*2
                    double help = Double.parseDouble(str[i + 1]);
                    double ans = s.peek();// 取出栈顶元素
                    s.pop();// 消栈
                    ans *= help;
                    s.push(ans);
                }

                if (str[i].compareTo("/") == 0) {
                    double help = Double.parseDouble(str[i + 1]);
                    double ans = s.peek();
                    s.pop();
                    ans /= help;
                    s.push(ans);
                }

                if (str[i].compareTo("%") == 0) {
                    double help = Double.parseDouble(str[i + 1]);
                    double ans = s.peek();
                    s.pop();
                    ans %= help;
                    s.push(ans);
                }       
            }
        }
        double ans = 0d;
        while (!s.isEmpty()) {
            ans += s.peek();
            s.pop();
        }
        String result = String.valueOf(ans);
        return result;
    }
}

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

高二的笔记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值