2016/4/30

不定長度引數

http://www.codedata.com.tw/book/java-basic-source/ch11-2.htm


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20


public class SimpleAdder{
    public int sumOf(int... params){
        int sum = 0;
        for (int i = 0; i < params.length; i++){
            sum = sum + params[i];
        }
        return sum;
    }
 
    public static void main(String[] args){
        SimpleAdder adder = new SimpleAdder();
        System.out.print("1+2+3=");
        System.out.print("1+2+3+4=");
        System.out.print("1+2=");
        System.out.println(adder.sumOf(1, 2));
        System.out.println(adder.sumOf(1, 2, 3));
        System.out.println(
                adder.sumOf(1, 2, 3, 4));
    }}



沒有留言:

張貼留言