第一步:创建类Student,用来定义学生的属性和方法
package cn.itcast.demo5;
public class Student {
private String name ;
private int age ;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
第二步:创建CallName类,用来实现点名器的功能
package cn.itcast.demo5;
import java.util.ArrayList;
import java.util.Random;
public class CallName {
public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<Student>();
//以下为调用方法
addStudent(list);
printStudent(list);
randomStudent(list);
}
public static void addStudent(ArrayList<Student> list) {
Student stu1 = new Student();
Student stu2 = new Student();
Student stu3 = new Student();
stu1.setName("小顾");
stu2.setName("小郭");
stu3.setName("小范");
stu1.setAge(20);
stu2.setAge(22);
stu3.setAge(23);
list.add(stu1);
list.add(stu2);
list.add(stu3); //将元素导入数组
}
public static void printStudent(ArrayList<Student> list) {
for (int i = 0; i < list.size(); i++) {
Student stu = list.get(i);
System.out.println(stu.getAge()+" "+stu.getName());
}
}
public static void randomStudent(ArrayList<Student> list) {
Random ran = new Random();
int index = ran.nextInt(list.size()); //从0到集合长度中间生成随机整数
Student stu =list.get(index);
System.out.println("随机点到的学生为:"+stu.getName());
}
}
|
|