1. 程式人生 > >形參個數可變的方法

形參個數可變的方法

定義方法時,在最後一個形參的型別後增加三點(...),則表明該形參可以接受多個引數值,多個引數值被當成陣列傳入 形參個數可變的引數本質就是一個數組引數,如: public static void test(int a,String...books); public static void test(int a,String[] books); 這兩種方法的效果一樣。

  例如:

定義一個教師類,包含姓名、性別、職稱、年齡、基本工資
定義兩個構造方法:
(1) 採用姓名、性別、年齡作為引數
(2) 將姓名、性別、職稱、年齡、基本工資作為引數進行初始化,
普通方法:
(1) 輸出教師的姓名、年齡、職稱
(2) 輸出教師的平均基本工資
(3) 輸出教師的平均年齡
 1 public class Answer {
 2     public static void main(String[] args) {
 3         Teacher teacher1 = new Teacher("111","男","222",20,"9999");
4 Teacher teacher2 = new Teacher("123","女","222",21,"8888"); 5 new Teacher().print1(teacher1); 6 new Teacher().print2(teacher1,teacher2); 7 new Teacher().print3(teacher1,teacher2); 8 } 9 10 } 11 class Teacher{ 12 private String name; 13 private String sex;
14 private String value; 15 private int age; 16 private String sala; 17 18 public Teacher() { 19 } 20 public Teacher(String name, String sex, int age) { 21 super(); 22 this.name = name; 23 this.sex = sex; 24 this.age = age; 25 } 26 public
Teacher(String name, String sex, String value, int age, String sala) { 27 super(); 28 this.name = name; 29 this.sex = sex; 30 this.value = value; 31 this.age = age; 32 this.sala = sala; 33 } 34 public void print1(Teacher teacher) { 35 System.out.println(teacher.name ); 36 System.out.println(teacher.age ); 37 System.out.println(teacher.sala ); 38 } 39 public void print2(Teacher...teacher) { 40 int sum = 0; 41 for(int i = 0;i<teacher.length ;i++) { 42 sum += Integer.parseInt(teacher[i].value ); 43 } 44 System.out.println(sum/teacher.length ); 45 } 46 public void print3(Teacher...teacher) { 47 int sum = 0; 48 for(int i = 0;i<teacher.length ;i++) { 49 sum += teacher[i].age; 50 } 51 System.out.println(sum/teacher.length ); 52 } 53 }

元素個數不清楚的(可以無數個,可以0個)