基本概念
java 允许将同一个类中多个同名同功能但参数个数不同的方法,封装成一个方法。
就可以通过可变参数实现
基本语法
访问修饰符 返回类型 方法名(数据类型... 形参名) {
}
//可以计算 2 个数的和,3 个数的和 , 4. 5, 。。 public class Test3 { public static void main(String[] args){ HspMethod n = new HspMethod(); System.out.println(n.sum(50 , 60 , 99)); System.out.println(n.sum(50 , 60 , 56 , 88 , 174)); } } class HspMethod{ public int sum(int... nums){ //int... 表示可以接受0-多个参数 int res = 0; for (int i = 0 ; i < nums.length ; i++){ res += nums[i]; } return res; } }
注意事项
练习
public class Test3 { public static void main(String[] args){ HspMethod n = new HspMethod(); System.out.println(n.showScore("蔡徐坤" , 66 , 56 , 76 , 46)); } } class HspMethod{ public String showScore(String name , double... scores){ double sum = 0; for (int i = 0 ; i < scores.length ; i++){ sum += scores[i]; } return name + scores.length + "门课的总成绩为:" + sum; } }