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;
// }
}
集合框架_可变参数的概
最新推荐文章于 2021-12-21 21:47:00 发布