可变参数的作用
在一个类里,使用一个方法,就可以做到同功能多个参数或没有参数的使用
优点:可以降低代码的重复率
格式为
访问修饰符 返回类型 方法名 (数据类型 ... 形参名) {
}
形参数是一个数组
class Method {
public int sum (int ... nums) {
int n = 0;
for (int i = 0; i < nums.length; i++) {
n += nums[i];
}
return n;
}
}
在主方法中new一个对象,然后调用上面类中的方法
public static void main(String[] args) {
Method m = new Method();
System.out.println("和相加为" + (m.sum(2,4,4)));
System.out.println("和相加为" + (m.sum(5,15)));
System.out.println("和相加为" + (m.sum()));
}
}
就可以在控制器中得到结果
可变参数也可以使用直接将数组放进实参
public static void main(String[] args) {
T t1 =new T();
int arr[] = {1,5,7};
System.out.println(t1.f1(arr));
}
}
class T {
public int f1 (int ... nums) {
int n = 0;
for (int i = 0; i < nums.length; i++) {
n += nums[i];
}
System.out.println("长度为" + nums.length);
return n;
}
可变参数可以和别的参数放在一起,但形参里只能有一个可变参数类型,且一定要放置在最后
public static void main(String[] args) {
Method1 m = new Method1();
System.out.println(m.Score("101宿舍", 35 , 35, 58, 58));
}
}
class Method1 {
public String Score (String str , int ... age) {
int n1 = 0;
for (int i = 0; i < age.length; i++) {
n1 += age[i];
}
return str + "的 " + age.length + " 个人年龄总和为 "+ n1;
}