[JAVA]switch case default

 

 

public class Calculator
{
    public static void main(String[] args)
    {
        //为了避免magic number,采取定义变量
        double n1, n2;
        n1 = 56;
        n2 = 65;
        System.out.println(calc(n1, n2, '+'));
        System.out.println(calc(n1, n2, '-'));
        System.out.println(calc(n1, n2, '*'));
        System.out.println(calc(n1, n2, '/'));
        System.out.println(calc(n1, n2, ')'));
    }
    static double calc(double num1, double num2, char operator)
    {
        double result = 0.0;
        switch(operator)
        {
            case '+': result = num1 + num2; break; //注意:如果直接return num1 + num2; break; 最后的break就unreachable
            case '-': result = num1 - num2; break; //所以采用定义新变量result来解决
            case '*': result = num1 * num2; break;
            case '/': result = num1 / num2; break;
            default: result = 0;
        }
        return result;
    }
}

 

posted @ 2020-06-09 21:54  profesor  阅读(600)  评论(0编辑  收藏  举报