Educoder-学习-Java类和对象之可变参数

掌握知识点

  • …可变长形参(如:string… name,具体看下面代码)
  • 一维数组的灵活控制

(第一题)通关源码

public class Student {

	public static void print(String... name){
		
		System.out.println("本次参加考试的有"+name.length+"人,名单如下:");
		for (int i = 0 ; i < name.length; i++){
			System.out.println(name[i]);
		}
	}	
}
public class Demo{
    public static void main(String[] args) {
        Student student = new Student();
        student.print("张强","李成","王勇");    // 传入3个值
        student.print("马丽","陈玲");
    }
}

(第二题)通关源码

public class Add {

    public static int add(int... a){
        int sum = 0;
        for (int i = 0; i < a.length; i++){
            sum = sum + a[i];
        }
        return sum;
    }

}
public class Demo {
    public static void main(String[] args) {
        System.out.println("add(25,36)的值为:"+Add.add(25,36));
        System.out.println("add(58,96,754)的值为:"+Add.add(58,96,754));
    }
}

2分钟通关,比某些人抄答案还要快!!
Educoder-学习-Java类和对象之可变参数_第1张图片

你可能感兴趣的:(Educoder攻略,java,开发语言,后端)