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();
}

    }
 

  • 39
    点赞
  • 410
    收藏
    觉得还不错? 一键收藏
  • 12
    评论
### 回答1: 好的,这里提供一份基本的 Java 计算器代码: ```java import java.util.Scanner; public class Calculator { public static void main(String[] args) { Scanner input = new Scanner(System.in); double num1, num2, result; char operator; System.out.print("Enter first number: "); num1 = input.nextDouble(); System.out.print("Enter operator (+, -, *, /): "); operator = input.next().charAt(0); System.out.print("Enter second number: "); num2 = input.nextDouble(); switch (operator) { case '+': result = num1 + num2; break; case '-': result = num1 - num2; break; case '*': result = num1 * num2; break; case '/': result = num1 / num2; break; default: System.out.println("Invalid operator."); return; } System.out.println(num1 + " " + operator + " " + num2 + " = " + result); } } ``` 这个程序可以让用户输入两个数字和一个操作符(加、减、乘、除),然后计算并输出结果。需要注意的是,这个程序没有做输入验证,所以要保证用户输入的是正确的数字和操作符。 ### 回答2: 计算器是非常常用的工具,可以帮助我们进行数学运算。下面是一个使用Java编写的简单计算器示例: ``` import java.util.Scanner; public class Calculator { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("请输入第一个数字:"); double num1 = scanner.nextDouble(); System.out.print("请输入运算符(+、-、*、/):"); String operator = scanner.next(); System.out.print("请输入第二个数字:"); double num2 = scanner.nextDouble(); double result; switch (operator) { case "+": result = num1 + num2; System.out.println("结果:" + result); break; case "-": result = num1 - num2; System.out.println("结果:" + result); break; case "*": result = num1 * num2; System.out.println("结果:" + result); break; case "/": if (num2 == 0) { System.out.println("除数不能为0"); } else { result = num1 / num2; System.out.println("结果:" + result); } break; default: System.out.println("无效的运算符"); } scanner.close(); } } ``` 以上示例代码中,我们使用`Scanner`类从控制台获取用户输入的数字和运算符。然后,根据运算符进行相应的数学运算,并输出结果。如果用户输入的是除法,并且除数为0,则会提示"除数不能为0"。最后,我们关闭了`Scanner`对象。 这个简单的计算器可以进行加、减、乘、除四种基本运算,并对不合法的输入进行了判断和处理。但请注意,这个计算器只能处理双精度浮点数的运算结果。如需扩展功能,还可以进一步完善代码,例如添加对括号、指数运算等的支持。 ### 回答3: 要用Java写一个计算器,可以按照以下步骤来实现: 1. 创建一个Java类,命名为"Calculator"。 2. 在Calculator类中,定义各种方法来执行不同的计算操作,例如加法、减法、乘法和除法。这些方法可以接受两个参数(即需要计算的两个数值),并返回计算结果。 3. 使用Java的Scanner类,以便从用户那里获取输入。通过提示用户输入数值和运算符,然后使用Scanner类对这些输入进行读取。 4. 在Calculator类中,使用条件语句(例如if-else语句)来确定用户输入的运算操作符,并调用相应的计算方法。 5. 在main方法中,创建Calculator类的一个实例,并调用相应的方法进行计算。将计算结果显示给用户。 6. 使用循环语句(例如while或do-while语句),可以让用户多次进行计算,直到用户选择退出程序为止。 示例代码如下: ``` import java.util.Scanner; public class Calculator { public static int add(int num1, int num2) { return num1 + num2; } public static int subtract(int num1, int num2) { return num1 - num2; } public static int multiply(int num1, int num2) { return num1 * num2; } public static int divide(int num1, int num2) { return num1 / num2; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Calculator calculator = new Calculator(); char operator; int num1, num2, result; String choice; do { System.out.print("Enter the first number: "); num1 = scanner.nextInt(); System.out.print("Enter the operator (+, -, *, /): "); operator = scanner.next().charAt(0); System.out.print("Enter the second number: "); num2 = scanner.nextInt(); if (operator == '+') { result = calculator.add(num1, num2); System.out.println("Result: " + result); } else if (operator == '-') { result = calculator.subtract(num1, num2); System.out.println("Result: " + result); } else if (operator == '*') { result = calculator.multiply(num1, num2); System.out.println("Result: " + result); } else if (operator == '/') { result = calculator.divide(num1, num2); System.out.println("Result: " + result); } else { System.out.println("Invalid Operator!"); } System.out.print("Do you want to perform another calculation? (yes/no): "); choice = scanner.next(); } while (choice.equalsIgnoreCase("yes")); scanner.close(); } } ``` 这段代码实现了一个简单的计算器,它可以进行加法、减法、乘法和除法运算。用户可以根据程序的提示输入数值和运算符,然后得到计算结果。如果用户想要继续计算,可以选择输入"yes",否则可以选择输入"no"来退出程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值