package lijun.cn.demo1;
public class Student {
//描述学生 属性 姓名 年龄
String name;
int age;
}
package lijun.cn.demo1;
import java.util.ArrayList;
import java.util.Random;
public class CallName {
public static void main(String[] args) {
//1 定义集合 存储的是Student类型
ArrayList<Student> array= new ArrayList<Student>();
// 2 调用添加的方法
add(array);
//3 遍历集合
printArrayList(array);
//4 随机点名
randomStudentNmae(array);
}
//4.1 随机点名
public static void randomStudentNmae(ArrayList<Student> array){
Random r = new Random();
//生成随机数的范围
int num = r.nextInt(array.size());
//随机数num 当成array集合的索引 从而获得名字和年龄
Student s = array.get(num);
System.out.println("=============");
System.out.println(s.name+" "+s.age);
}
//3.1遍历集合
public static void printArrayList(ArrayList<Student> array){
for (int i = 0; i < array.size(); i++) {
Student s = array.get(i);
System.out.println(s.name+" "+s.age);
}
}
// 2 .1书写添加的方法
public static void add(ArrayList<Student> array){
Student s1 = new Student();
s1.name="张无忌";
s1.age=22;
Student s2 = new Student();
s2.name="无双";
s2.age=21;
Student s3 = new Student();
s3.name="建宁";
s3.age=20;
Student s4 = new Student();
s4.name="龙儿";
s4.age=25;
//将4个人的名字和年龄存储到集合中
array.add(s1);
array.add(s2);
array.add(s3);
array.add(s4);
}
}