Java编写简单计算器

Java编写简单计算器

1、定义四个方法完成加减乘除

接收2个浮点型数,返回相应操作结果:

//加法
    public static double add(double num1,double num2){
        return num1+num2;
    }

    //减法
    public static double decrease(double num1,double num2){
        return num1-num2;
    }

    //乘法
    public static double multiplication(double num1,double num2){
        return num1*num2;
    }

    //除法
    public static double division(double num1,double num2){
        return num1/num2;
    }

2、使用Scanner进行用户交互,使用switch循环调用加减乘除方法

Scanner scanner = new Scanner(System.in);

        System.out.println("请输入第一个数字:");
        double num1 = scanner.nextDouble();

        System.out.println("请输入运算符:");
        String operator = scanner.next();

        System.out.println("请输入第二个数字:");
        double num2 = scanner.nextDouble();
        double result = 0;
        switch (operator){
            case "+":
                result = add(num1,num2);
                break;
            case "-":
                result = decrease(num1,num2);
                break;
            case "*":
                result = multiplication(num1,num2);
                break;
            case "/":
                result = division(num1,num2);
                break;
            default:
                System.out.println("非法输入!");
        }
        System.out.println(result);

        scanner.close();

3、运行结果

Java编写简单计算器

上一篇:acwing kuangbin专题打卡第一题棋盘问题


下一篇:Dungeon Master(题目地址链接:https://acs.jxnu.edu.cn/problem/NOIOPJCH02051253)