Student.java
package com.yikuan.test; public class Student { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
CallName.java
package com.yikuan.test; import java.util.ArrayList; import java.util.Random; /** * 随机点名器 * 1.创建一个集合,将学生对象存储到集合中 * 2.总览所有学生信息,将存储到集合中的Student对象遍历出来 * 3.随机一个学生,随机数作为索引到集合中去查找元素 * @author Administrator * */ public class CallName { public static void main(String[] args) { //定义一个集合,存储学生对象 ArrayList<Student> array = new ArrayList<Student>(); addStudent(array); printStudent(array); System.out.println("点到的学生:---->------->----->"); randomStudent(array); } /*定义一个方法,存储学生对象到集合中*/ public static void addStudent(ArrayList<Student> array){ Student s1 = new Student(); s1.setName("李四"); s1.setAge(14); Student s2 = new Student(); s2.setName("李四2"); s2.setAge(145); Student s3 = new Student(); s3.setName("李四3"); s3.setAge(146); Student s4 = new Student(); s4.setName("李四4"); s4.setAge(142); Student s5 = new Student(); s5.setName("李四5"); s5.setAge(143); array.add(s1); array.add(s2); array.add(s3); array.add(s4); array.add(s5); } /*遍历集合*/ public static void printStudent(ArrayList<Student> array){ for (int i = 0; i < array.size(); i++) { Student s = array.get(i); System.out.println(s.getName()+"...."+s.getAge()); } } /*随机数生成学生信息*/ public static void randomStudent(ArrayList<Student> array){ Random r = new Random(); int index = r.nextInt(array.size()); Student s = array.get(index); System.out.println(s.getName()); } }