形参个数可变的方法
Posted zcx-blog
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了形参个数可变的方法相关的知识,希望对你有一定的参考价值。
定义方法时,在最后一个形参的类型后增加三点(...),则表明该形参可以接受多个参数值,多个参数值被当成数组传入
形参个数可变的参数本质就是一个数组参数,如:
public static void test(int a,String...books);
public static void test(int a,String[] books);
这两种方法的效果一样。
例如:
定义一个教师类,包含姓名、性别、职称、年龄、基本工资
定义两个构造方法:
(1) 采用姓名、性别、年龄作为参数
(2) 将姓名、性别、职称、年龄、基本工资作为参数进行初始化,
普通方法:
(1) 输出教师的姓名、年龄、职称
(2) 输出教师的平均基本工资
(3) 输出教师的平均年龄
定义两个构造方法:
(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个)
以上是关于形参个数可变的方法的主要内容,如果未能解决你的问题,请参考以下文章