学习Java一点心得——可变参数

可变参数的作用

在一个类里,使用一个方法,就可以做到同功能多个参数或没有参数的使用

优点:可以降低代码的重复率

格式为

访问修饰符 返回类型 方法名 (数据类型 ... 形参名) {

}

形参数是一个数组

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;
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值