用java做简单的计算器类,实现两个数字的加减乘除运算

2019-11-02 00:00:00 两个 运算 加减乘除

计算器类

package calculator;
import java.util.Scanner;
public class Calculator{
    private float number1;
    private float number2;
    private float addresult;
    private float minusresult;
    private float multipleresult;
    private float divideresult;
    public Calculator() {
    }
    public Calculator(float number1,float number2) {
        this.number1=number1;
        this.number2=number2;
    }
    //加法的实现
    public float add(){
        System.out.println(number1+"+"+number2+"="+(number1+number2));
        return addresult;
    }
    //减法的实现
    public float minus() {
        System.out.println(number1+"-"+number2+"="+(number1-number2));
        return minusresult;
    }
    //乘法的实现
    public float multiple() {
        System.out.println(number1+"*"+number2+"="+(number1*number2));
        return multipleresult;
    }
    //除法的实现
    public float divide() {
        if(number2==0.0f) {
            System.out.println("0不能做除数");
        }
        else {
        System.out.println(number1+"/"+number2+"="+(number1/number2));
        }
        return divideresult;
    }
}

测试类如下

package calculator;
import java.util.Scanner;
public class Test  {
public static void main(String[] args) {
        // TODO Auto-generated method stub
                System.out.println("***********************");
                System.out.println("欢迎使用计算机系统");
                System.out.println("请输入两个数字");
        Scanner sc=new Scanner(System.in);
        float number1=sc.nextFloat();
        float number2=sc.nextFloat();
        Calculator c=new Calculator(number1,number2);
                System.out.println("请输入要进行的操作序号。");
                System.out.println("1,两数相加。   2,两数相减。  3,两数相乘。  4,两数相除");
                System.out.println("************************");
                int s;
                s=sc.nextInt();
        switch(s){
                    case 1:
                        c.add();
                        break;
                    case 2:
                        c.minus();
                        break;
                    case 3:
                        c.multiple();
                        break;
                    case 4:
                        c.divide();
                        break;     
                }
        sc.close();
    }
}

新手学习,还请多指教。

相关文章