集合框架_可变参数的概

package cn.itcast_03;

/*
 * 可变参数:定义方法的时候不知道该定义多少个参数
 * 		格式:
 * 			修饰符 返回值类型 方法名(数据类型... 变量名){
 * 	
 * 			}
 * 
 * 		注意:
 * 			A:这里的变量其实是一个的数组。
 * 			B:如果一个方法有可变参数,并且有多个参数,那么,可变参数肯定是最后一个
 */
public class ArgsDemo {
	public static void main(String[] args) {
		// 2个数据求和
		int a = 10;
		int b = 20;
		int result = sum(a, b);
		System.out.println("result:" + result);

		// 3个数据求和
		int c = 30;
		result = sum(a, b, c);
		System.out.println("result:" + result);

		// 4个数据求和
		int d = 30;
		result = sum(a, b, c, d);
		System.out.println("result:" + result);

		// 需求:我要写一个求和的功能,到低是几个数据求和呢,我不太清楚,但是我知道我在调用的时候我就知道了。
		// 为了解决这个问题,Java就提供了一个东西:可变参数
		result = sum(a, b, c, d, 40);
		System.out.println("result:" + result);

		result = sum(a, b, c, d, 40, 50);
		System.out.println("result:" + result);
	}

	public static int sum(int b,int... a) {
		// System.out.println(x);
		// return 0;

		int s = 0;
		for (int x : a) {
			s += x;
		}
		return s;
	}

	// public static int sum(int a, int b, int c, int d) {
	// return a + b + c + d;
	// }
	//
	// public static int sum(int a, int b, int c) {
	// return a + b + c;
	// }
	//
	// public static int sum(int a, int b) {
	// return a + b;
	// }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值