java 简易计算器

要求:

1.使用Java图形界面组件设计软件,界面如图所示。

2.软件能够满足基本的“加、减、乘、除”等运算要求。

3.程序代码清晰,语法规范,结构合理,逻辑正确。

效果图:

2b9091ad8bc94af0b2f3af902ac72003.png

先分析,计算器大概是由三个大部分组成的:菜单栏,显示框,按钮。

所以定义一个类cal继承JFrame。

class cal extends JFrame  {
    private JPanel p1, p2;
    private JTextArea show;
    private String box ;
    JMenuBar menubar;//菜单
    JMenu menu1, menu2, menu3;//菜单

    StringBuffer strA;//用来存放用户输入的第一个数字
    StringBuffer strB;//用来存放用户输入的第二个数字

char oper ='~';//初始化操作符,可以随便初始化一个特殊符号,这里只是用来区分的
    double  A;
    double  B;
    private String[] text2 = {"C", "CE","%", "/",
            "7", "8", "9", "*",
            "4", "5", "6", "-",
            "1", "2", "3", "+",
            "DEL","0", ".", "="};//计算器按钮面板

    private JButton[] munButton = new JButton[text2.length];


}

我们定义完后开始初始化。

class cal extends JFrame implements ActionListener {
    private JPanel p1, p2;
    private JTextArea show;
    private String box ;
    JMenuBar menubar;
    JMenu menu1, menu2, menu3;
    StringBuffer strA;
    StringBuffer strB;



    char oper ='~';
    double  A;
    double  B;
    private String[] text2 = {"C", "CE","%", "/",
            "7", "8", "9", "*",
            "4", "5", "6", "-",
            "1", "2", "3", "+",
            "DEL","0", ".", "="};//计算器按钮面板
    private JButton[] munButton = new JButton[text2.length];





    public cal() {
        p1 = new JPanel();
        p2 = new JPanel();
        show = new JTextArea();
        p1.setSize(600, 100);
        menubar = new JMenuBar();
        menu1 = new JMenu("查看(V)");
        menu2 = new JMenu("编辑(E)");
        menu3 = new JMenu("帮助(H)");

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


    }



    public void init() {//初始化
        this.setTitle("计算器");//设置名称
        this.setBounds(200, 200, 320, 300);

        this.setLayout(new BorderLayout());//设置布局

        this.add(p1, BorderLayout.CENTER);
        this.add(p2, BorderLayout.SOUTH);
        menubar.add(menu1);
        menubar.add(menu2);
        menubar.add(menu3);
        this.setJMenuBar(menubar);
        this.setLocationRelativeTo(null);//放置在屏幕中央
        this.setResizable(false);//固定大小,用户不能调整大小

        show.setPreferredSize(new Dimension(300, 100));
        p1.add(show);
        p2.setLayout(new GridLayout(5, 4, 2, 3));
        //添加数字按键
        for (int i = 0; i < text2.length; i++) {
            munButton[i] = new JButton(text2[i] + " ");
            p2.add(munButton[i]);
        }



        for (int i = 0; i < munButton.length; i++)
            munButton[i].addActionListener(this);

        this.setVisible(true);//窗体可视化


        this.addWindowListener(new WindowAdapter() {//监听事件,当按下关闭按钮时,结束程序

            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

    }

接着我们就开始进入到这个项目的最重要的部分了。

设置按钮监听事件,通过获取按钮的信息来进行判断运算。

在我们进行加减乘除计算的时候会出现一个特殊情况,除数为0,所以我们要预防出现异常影响程序的运行,我们就要进行异常的捕获处理,这里我是自定义了一个异常类munber_Exception,然后我们利用try{}catch{}语句来进行异常捕获和处理。

    public double division(double x,double y)throws munber_Exception{

        if(y==0){
            throw new munber_Exception("除数不能为0!");
        }
        else{
            return x/y;
        }


    }
    @Override
    public void actionPerformed(ActionEvent e) {
        try { String act=e.getActionCommand();//这个方法返回的是事件源组件的“命令” , 这个“命令” 实际上就是事件源组件上的“Label(标签)字符串”,即如果我按了“9”这个按钮他就会返回一个“9的值”

        char a=act.charAt(0);//取act这个字符串的首字符
        if (a=='0' ||a=='1' || a=='2' ||a=='3'||a=='4'||a=='5'||a=='6'||a=='7'||a=='8'||a=='9'||a=='.') {
            if(oper=='~'){//当oper=='~'时,则操作符为空
                strA.append(a);
                show.setText(String.valueOf(strA));


            }else {
                strB.append(a);
                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));
               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));

                   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);}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=='D'){//删除
                 if(oper!='~'){
                     if(strB.length()>0){
                         strB.delete(strB.length()-1,strB.length());
                         show.setText(String.valueOf(strA)+oper+String.valueOf(strB));
                     }
                     else
                         show.setText("0");
                 }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");
    }

    }

完整代码如下:

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 p1, p2;
    private JTextArea show;
    private String box ;
    JMenuBar menubar;
    JMenu menu1, menu2, menu3;
    StringBuffer strA;
    StringBuffer strB;



    char oper ='~';
    double  A;
    double  B;
    private String[] text2 = {"C", "CE","%", "/",
            "7", "8", "9", "*",
            "4", "5", "6", "-",
            "1", "2", "3", "+",
            "DEL","0", ".", "="};//计算器按钮面板
    private JButton[] munButton = new JButton[text2.length];

    public cal() {
        p1 = new JPanel();
        p2 = new JPanel();
        show = new JTextArea();
        p1.setSize(600, 100);
        menubar = new JMenuBar();
        menu1 = new JMenu("查看(V)");
        menu2 = new JMenu("编辑(E)");
        menu3 = new JMenu("帮助(H)");

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


    }



    public void init() {//初始化
        this.setTitle("计算器");
        this.setBounds(200, 200, 320, 300);

        this.setLayout(new BorderLayout());

        this.add(p1, BorderLayout.CENTER);
        this.add(p2, BorderLayout.SOUTH);
        menubar.add(menu1);
        menubar.add(menu2);
        menubar.add(menu3);
        this.setJMenuBar(menubar);
        this.setLocationRelativeTo(null);
        this.setResizable(false);

        show.setPreferredSize(new Dimension(300, 100));
        p1.add(show);
        p2.setLayout(new GridLayout(5, 4, 2, 3));
        //添加数字按键
        for (int i = 0; i < text2.length; i++) {
            munButton[i] = new JButton(text2[i] + " ");
            p2.add(munButton[i]);
        }



        for (int i = 0; i < munButton.length; i++)
            munButton[i].addActionListener(this);

        this.setVisible(true);


        this.addWindowListener(new WindowAdapter() {
            @Override
            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;
        }


    }
    @Override
    public void actionPerformed(ActionEvent e) {
        try { String act=e.getActionCommand();
        char a=act.charAt(0);
        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);
                show.setText(String.valueOf(strA));


            }else {
                strB.append(a);
                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));
               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));

                   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);}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=='D'){
                 if(oper!='~'){
                     if(strB.length()>0){
                         strB.delete(strB.length()-1,strB.length());
                         show.setText(String.valueOf(strA)+oper+String.valueOf(strB));
                     }
                     else
                         show.setText("0");
                 }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();
}

    }
 

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
扎眼的阳光的头像扎眼的阳光普通用户
上一篇 2023年12月22日
下一篇 2023年12月22日

相关推荐