Java实训——计算器(四则运算以及其他功能)

大二下新人java实训实现计算器,其中的代码是参考csdn博主的,注释多是为了方便自己理解,结尾会放文章链接。

以下是代码的一些分析:

细节讲解:

1 单独添加两个按钮Backspace和C:

setLayout()布局管理器,需要精确指定各个组建的大小和位置,就需要用到空布局。

2 网格布局设置按钮:(网上学习的)

使用字符串数组( text2[ ] )存储需要的计算器按钮面板

自定义按钮类数组,定义了一共text2.length个按钮,先用getContentPane()方法获取JFrame的内容面板,然后通过for循环添加按钮,以及实现监听功能。

3 act获取被点击按钮的名称,a获取act的第一个字符,如果是数字且操作符为默认值则继续往strA中添加字符;若操作符不为默认值,则往strB中添加字符

对于绝对值、开平方和回退功能,我用al获取它们的第三个字符,分别是-、r和c,如果识别到al等于对应字符,则进入相应功能。
方法:

append()可以把括号内任意类型的数据添加到字符串缓冲区里面,并返回字符串缓冲区本身。

.valueOf()用于将基本数据类型转换为String类型,补充一点,type不能为null,不然会报空指针异常。

charAt(索引):返回对应索引的字符。

将StringBuffer类型的strA转换为string,再转换为double类型。

不足:

       不能进行三个数及以上的运算:2+2+2

代码:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

//异常处理
class munber_Exception  extends Exception{
    String e;
    public munber_Exception(){}
    public munber_Exception(String message){
        this.e=message;
    }
    public String shows(){
        return e;
    }
}

class cal extends JFrame implements ActionListener {
    private JPanel  panel;//定义面板对象名
    private JTextArea show;//文本区(JTextArea),它是窗体中一个放置文本的区域。
    StringBuffer strA;
    StringBuffer strB;



    char oper ='~';
    double  A;
    double  B;
    private String[] text2 =
            {"7", "8", "9", "/",
                    "4", "5", "6", "*",
                    "1", "2", "3", "-",
                    "0","+/-", ".", "+",
                    "1/x", "%","sqrt", "=",};//用字符串数组存储计算器按钮面板
    private JButton[] munButton = new JButton[text2.length];//自定义按钮类数组

    public cal() {
        panel = new JPanel();
        show = new JTextArea();

        strB=new StringBuffer();
        strA=new StringBuffer();
    }



    public void init() {//初始化
        //getContentPane()方法和add()方法添加组件(输入框和B、C按钮),再使用网格布局添加余下的数字和操作符按钮
        this.setTitle("计算器");
        this.setBounds(900, 300, 316, 288);
        this.setResizable(false);

        show.setBounds(0,0,300,30);
        this.getContentPane().add(show);//用getContentPane()方法获得JFrame的内容面板,用add()方法在面板添加输入框


        //单独设置两个按钮 Backpace和C
        JButton btnCe_1 = new JButton("Backspace");//setLayout()布局管理器,需要精确指定各个组建的大小和位置,就需要用到空布局。
        this.getContentPane().setLayout(null);//设置为null布局(空布局)。
        // 在已经接入监听器的类中使用addActionListener事件监听器监听按钮
        btnCe_1.addActionListener(this);


        btnCe_1.setBounds(0, 30, 150, 30);//设置组件在容器中的大小和位置
        this.getContentPane().add(btnCe_1);


        JButton btnCe = new JButton("C");
        btnCe.addActionListener(this);
        btnCe.setBounds(150, 30, 150, 30);
        this.getContentPane().add(btnCe);



        panel.setBounds(0, 60, 300, 190);
        panel.setLayout(new GridLayout(5, 4));
        this.getContentPane().add(panel);//用getContentPane()方法获得JFrame的内容面板,用add()方法在面板添加
        //添加按键
        for (int i = 0; i < text2.length; i++) {
            munButton[i] = new JButton(text2[i] + " ");
            panel.add(munButton[i]);
        }



        for (int i = 0; i < munButton.length; i++)//实现每个按钮的监听功能
            munButton[i].addActionListener(this);

        this.setVisible(true);


        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

    }

    //乘法运算
    public double division(double x,double y)throws munber_Exception {
        if (y == 0) {
            throw new munber_Exception("除数不能为0!");
        } else {
            return x / y;
        }

    }

    //事件触发ActionEvent事件后,监视器调用接口中的方法actionPerformed(ActionEvent e)对发生的事件做出处理
    /*因为每按一次按钮就进入处理功能一次,所以a一直在接收按钮传递过来的值.strA和strB用来存储值
    如果a仍为~:则为strA继续添加字符;若不为~,则为strB添加字符;
    若识别到按钮输入的是操作符,则把操作符赋值给a
    若识别到按了=号,则开始运算,strA->A,strB->B使用方法获取A B值,j存储结果
     */
    public void actionPerformed(ActionEvent e) {
        try {
            String act=e.getActionCommand();//定义一个字符串获取按钮(组件)名称
            char a=act.charAt(0);//使用一个字符a获取act调用charAt(索引)后返回的值         charAt(索引):返回对应索引的字符
            char al='P';
            if(act.length()>2){
                al=act.charAt(2);//取巧:获取第三个值 c - r x
            }
            if (a=='0' ||a=='1' || a=='2' ||a=='3'||a=='4'||a=='5'||a=='6'||a=='7'||a=='8'||a=='9'||a=='.')
            {
                if(oper=='~'){
                    strA.append(a);//.append()可以把括号内任意类型的数据添加到字符串缓冲区里面,并返回字符串缓冲区本身
                    // .valueOf()用于将基本数据类型转换为String类型,补充一点,type不能为null,不然会报空指针异常
                    show.setText(String.valueOf(strA));
                }

                else {
                    strB.append(a);
                    show.setText(String.valueOf(strA)+oper+String.valueOf(strB));


                }

            }
            else if(a=='r'){
                if(strA.length()>0){
                    double Al=Double.parseDouble(String.valueOf(strA));//将StringBuffer类型的strA转换为string,再转换为double类型
                    strA.delete(0,strA.length());
                    strA.append(Math.sqrt(Al));
                    show.setText(String.valueOf(strA));
                }
            }
            else if(a=='x'){
                if(strA.length()>0){
                    double xl=Double.parseDouble(String.valueOf(strA));
                    if(xl==0){show.setText("除数不能为0");}
                    else{
                        strA.delete(0,strA.length());
                        strA.append(1/xl);
                        show.setText(String.valueOf(strA));}
                }
            }
            else if(al=='-')
            {
                if(oper=='~'){
                if(strA.length()>0){
                    double lA=Double.parseDouble(String.valueOf(strA));
                    if(lA>0){
                        strA.insert(0,'-');
                        show.setText(String.valueOf(strA));
                    }
                    else if(lA==0){show.setText(String.valueOf(strA));}
                    else{strA.deleteCharAt(0);show.setText(String.valueOf(strA));}
                    }
                }
                else{
                    double lB=Double.parseDouble(String.valueOf(strB));
                    if(strB.length()>0){
                        if(lB>0){
                            strB.insert(0,'-');
                            show.setText(String.valueOf(strA)+oper+String.valueOf(strB));
                        }
                        else if(lB==0){show.setText(String.valueOf(strB));}
                        else{strB.deleteCharAt(0);show.setText(String.valueOf(strA)+oper+String.valueOf(strB));}
                    }
                }
            }
            else if(a=='+'||a=='-'||a=='/'||a=='*'||a=='%'){
                oper=a;
                show.setText(String.valueOf(strA)+oper);

            }
            else if(a=='='){
                A = Double.parseDouble(String.valueOf(strA));//.parseDouble(“字符串”)将字符串值转换为double值。
                B = Double.parseDouble(String.valueOf(strB));
                double j;
                int len1=strA.length();
                int len2=strB.length();

                if (oper == '+') {
                    j = A + B;
                    show.setText(Double.toString(j));

                    strA.delete(0,len1);
                    strB.delete(0,len2);
                    strA.append(j);

                } else if (oper == '-') {
                    j = A - B;
                    show.setText(Double.toString(j));//toString(Double值)方法用于获取Double value / object的字符串值

                    strA.delete(0,len1);
                    strB.delete(0,len2);
                    strA.append(j);//支持了运算后再运算
                } else if (oper == '*') {
                    j = A * B;
                    show.setText(Double.toString(j));

                    strA.delete(0,len1);
                    strB.delete(0,len2);
                    strA.append(j);
                } else if (oper == '/') {
                    try{
                        j= division(A, B);show.setText(Double.toString(j));}
                    catch(munber_Exception u){
                        show.setText(u.shows());
                    }
                }
                else if (oper == '%') {
                    j = A % B;
                    show.setText(Double.toString(j));

                    strA.delete(0,len1);
                    strB.delete(0,len2);
                    strA.append(j);

                }
            }
            else if (a=='C') {
                show.setText(" ");
                oper='~';
                int len1=strA.length();
                int len2=strB.length();

                strA.delete(0,len1);
                strB.delete(0,len2);

            }
            else if (a=='c'){
                if(oper!='~'){
                    if(strB.length()>0){//有操作符有B
                        strB.delete(strB.length()-1,strB.length());
                        show.setText(String.valueOf(strA)+oper+String.valueOf(strB));
                    }
                }
                if(oper=='~'){
                    if(strA.length()>0){
                        strA.delete(strA.length()-1,strA.length());
                        show.setText(String.valueOf(strA));
                    }
                }
            }
        }catch(ArithmeticException m){
            System.out.println("除数不能为0");
        }

    }
}

public class Calculator {
    //调用
    public static void main(String[] args) {
        cal Calculator1 = new cal();
        Calculator1.init();
    }
}

布局学习:(20条消息) 简单计算器(Java实训)_Chien d'amis的博客-优快云博客

实现学习:(20条消息) java 简易计算器_︱Harvey︱的博客-优快云博客(其实就是两个版本的结合体)

简单的计算器 import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MyCalculator extends Frame implements ActionListener { JTextField txt = new JTextField(""); StringBuffer copyBoard=new StringBuffer(20); private String cmd = "="; private double result = 0;// 运算结果 private boolean start = true; StringBuffer strs=new StringBuffer(); class Window { Window() { Frame help=new Frame("关于作者"); help.setBounds(400,200,200,200); help.setVisible(true); help.setResizable(false); help.addWindowListener(new WindowAdapter() //关闭窗口 { public void windowClosing(WindowEvent e) { ((Frame)e.getSource()).dispose(); } } ); TextArea title = new TextArea(" 软件125实训项目 一 制作:第二组 常志铭 朱靖 2013.5.10 ",10,8,TextArea.SCROLLBARS_NONE); title.setBounds(50,50,200,30); title.setEditable(false); help.add(title); } } MyCalculator() { this.setTitle("我的计算器"); this.setBounds(400,150,225,320); this.createMenu(); this.createMainPanel(); this.addWindowListener(new WindowAdapter() //关闭窗口 { public void windowClosing(WindowEvent e) { System.exit(0); } } ); this.setResizable(false); this.setVisible(true); } private void createMenu() { MenuBar bar = new MenuBar(); this.setMenuBar(bar); Menu EditMenu = new Menu("编辑(E)"); Menu helpMenu = new Menu("帮助(H)"); bar.add(EditMenu); bar.add(helpMenu); MenuItem copyItem = new MenuItem("复制"); copyItem.setShortcut(new MenuShortcut(KeyEvent.VK_C,false)); EditMenu.add(copyItem); copyItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String temp = txt.getText().trim(); copyBoard.replace(0, copyBoard.length(), temp); } } ); MenuItem pasteItem = new MenuItem("粘帖"); pasteItem.setShortcut(new MenuShortcut(KeyEvent.VK_V,false)); EditMenu.add(pasteItem); pasteItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { txt.setText(copyBoard.toString()); result=(Double.parseDouble(copyBoard.toString())); } } ); MenuItem helpItem = new MenuItem("关于计算器"); helpItem.setShortcut(new MenuShortcut(KeyEvent.VK_H,false)); helpMenu.add(helpItem); helpItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { new Window(); } } ); } private void createMainPanel() { //整体面板 Panel Win = new Panel(null); Win.setSize(230, 330); Win.setVisible(true); //Win.setBackground(Color.black); this.add(Win); //显示 txt.setHorizontalAlignment(JTextField.RIGHT); txt.setBounds(5,5,210,50); txt.setFont(new java.awt.Font("Dialog", 1, 30)); txt.setEditable(false); Win.add(txt); //按键面板 Panel Butt = new Panel(null); Butt.setBounds(0, 50, 230, 280); //Butt.setBackground(Color.white); Butt.setVisible(true); Win.add(Butt); Button butx = new Button("C"); butx.setBounds(15,15,40,28); butx.addActionListener(this); butx.setFont(new java.awt.Font("Dialog", 1, 15)); Butt.add(butx); Button butz = new Button("←"); butz.setBounds(65,15,40,28); butz.setFont(new java.awt.Font("Dialog", 1, 20)); butz.addActionListener(this); Butt.add(butz); Button butcf = new Button("/"); butcf.setBounds(115,15,40,28); butcf.setFont(new java.awt.Font("Dialog", 0, 20)); butcf.addActionListener(this); Butt.add(butcf); Button butc = new Button("*"); butc.setBounds(165,15,40,28); butc.setFont(new java.awt.Font("Dialog", 1, 25)); butc.addActionListener(this); Butt.add(butc); Button but7 = new Button("7"); but7.setBounds(15,55,40,28); but7.setFont(new java.awt.Font("Dialog", 0, 15)); but7.addActionListener(this); Butt.add(but7); Button but8 = new Button("8"); but8.setBounds(65,55,40,28); but8.setFont(new java.awt.Font("Dialog", 0, 15)); but8.addActionListener(this); Butt.add(but8); Button but9 = new Button("9"); but9.setBounds(115,55,40,28); but9.setFont(new java.awt.Font("Dialog", 0, 15)); but9.addActionListener(this); Butt.add(but9); Button butjf = new Button("-"); butjf.setBounds(165,55,40,28); butjf.setFont(new java.awt.Font("Dialog", 0, 28)); butjf.addActionListener(this); Butt.add(butjf); Button but4 = new Button("4"); but4.setBounds(15,95,40,28); but4.setFont(new java.awt.Font("Dialog", 0, 15)); but4.addActionListener(this); Butt.add(but4); Button but5 = new Button("5"); but5.setBounds(65,95,40,28); but5.setFont(new java.awt.Font("Dialog", 0, 15)); but5.addActionListener(this); Butt.add(but5); Button but6 = new Button("6"); but6.setBounds(115,95,40,28); but6.setFont(new java.awt.Font("Dialog", 0, 15)); but6.addActionListener(this); Butt.add(but6); Button butj = new Button("+"); butj.setBounds(165,95,40,28); butj.setFont(new java.awt.Font("Dialog", 0, 20)); butj.addActionListener(this); Butt.add(butj); Button but1 = new Button("1"); but1.setBounds(15,135,40,28); but1.setFont(new java.awt.Font("Dialog", 0, 15)); but1.addActionListener(this); Butt.add(but1); Button but2 = new Button("2"); but2.setBounds(65,135,40,28); but2.setFont(new java.awt.Font("Dialog", 0, 15)); but2.addActionListener(this); Butt.add(but2); Button but3 = new Button("3"); but3.setBounds(115,135,40,28); but3.setFont(new java.awt.Font("Dialog", 0, 15)); but3.addActionListener(this); Butt.add(but3); Button bute = new Button("="); bute.setBounds(165,135,40,68); bute.setFont(new java.awt.Font("Dialog", 0, 25)); bute.addActionListener(this); Butt.add(bute); Button but0 = new Button("0"); but0.setBounds(15,175,90,28); but0.setFont(new java.awt.Font("Dialog", 0, 15)); but0.addActionListener(this); Butt.add(but0); Button butd = new Button("."); butd.setBounds(115,175,40,28); butd.setFont(new java.awt.Font("Dialog", 1, 25)); butd.addActionListener(this); Butt.add(butd); } public void actionPerformed(ActionEvent event) { String sf = event.getActionCommand(); if(sf.equals("9")||sf.equals("8")||sf.equals("7")||sf.equals("6")||sf.equals("5")||sf.equals("4")||sf.equals("3")||sf.equals("2")||sf.equals("1")||sf.equals("0")||sf.equals("C")||sf.equals("←")||sf.equals(".")) { String input = sf; if (start) { txt.setText(""); start = false; } if (input.equals("←")) { String str = txt.getText(); if (str.length() > 0) txt.setText(str.substring(0, str.length() - 1)); } else if (input.equals("C")) { txt.setText("0"); start = true; } else txt.setText(txt.getText() + input); } else { String command = sf; if (start) { cmd = command; } else { calculate(Double.parseDouble(txt.getText())); cmd = command; start = true; } } } public void calculate(double x) { if (cmd.equals("+")) result += x; else if (cmd.equals("-")) result -= x; else if (cmd.equals("*")) result *= x; else if (cmd.equals("/")) result /= x; else if (cmd.equals("=")) result = x; txt.setText("" + result); } public static void main (String[] args) { new MyCalculator(); } }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值