//1.可变性餐采用数组存储实参 //2.可变参数只能位于参数列表最后 //3.一个方法可变参数只有一个且必须位于参数列表最后
public class VarTest { public static void main(String[] args) { sum(10, 20, 30); sum2(10, 20, 30, 40); sum3(1,3,4,6); sum4(3.14,10,20,30); int maxNum=getMax(1,3,5,6,7,11,43,21,66); System.out.println("maxNum = " + maxNum); } static void sum(int i, int i1, int i2) { System.out.println(i+i1+i2); } static void sum2(int i, int i1, int i2, int i3) { System.out.println(i+i1+i2+i3); } //a是一个数组,代表参数 static void sum3(int... a){ for (int i = 0; i <a.length ; i++) { System.out.println(a[i]); } } static void sum4(double d1,int ...a){ double sums=0; for (int i = 0; i <a.length ; i++) { sums+=a[i]; } sums+=d1; System.out.println(sums); //输出63.14 } static int getMax(int ...arr2){ int maxNum=arr2[0]; for (int i = 1; i <arr2.length ; i++) { if (maxNum<arr2[i]){ maxNum=arr2[i]; } } return maxNum; } }
练习
返回字符串拼接结果,如果字符串为空,返回空
public class VarP { public static void main(String[] args) { String r1 = test("linzi","just"); System.out.println("r1 = " + r1); } public static String test(String... arr){ String result=""; for (int i = 0; i <arr.length ; i++) { result=result+arr[i]; } return result; } }