Java方法的重载和可变参数的使用

主方法和工具类:


public class Exer01 {
    public static void main(String[] args) {
        System.out.println("整数相加:" + new Tools().sum(1, 2, 3, 4));
        System.out.println("double和int相加:" + new Tools().sum(1.1, 2, 3, 4));
        System.out.println(new Tools().difference(2, 1));
        System.out.println(new Tools().difference(2.3, 1));
    }
}

class Tools {
    //方法的重载
    public int sum(int... num) {
        int sum = 0;
        for (int i = 0; i < num.length; i++) sum += num[i];
        return sum;
    }

    double sum(double... num) {
        double sum = 0;
        for (int i = 0; i < num.length; i++) sum += num[i];
        return sum;
    }

    int difference(int i, int j) {
        return i = i - j;
    }

    double difference(double i, double j) {
        return i - j;
    }
}

输出结果:

10
10.1
1
1.2999999999999998
上一篇:Android View 阴影的总结


下一篇:【BZOJ2157】旅游(树链剖分,Link-Cut Tree)