Java 案例八 随机点名系统(使用类实现,面向对象)

package cn.itcast.demo07;

import java.util.ArrayList;
import java.util.Random;


/*
 * 随机点名器:
 * 	1.创建集合,将Student对象存储到集合中
 *	2.总览所有学生的信息
 *		将存储到集合中的Student对象遍历
 *	3.随机学生
 *		随机数,作为索引,到集合中去查找元素
 *
 */
public class CallName {
	public static void main(String[] args){
		//定义集合ArrayList,存储Student类型
		ArrayList array = new ArrayList();
		addStudent(array);
		printStudent(array);
		randomStudent(array);
		
	}
	public static void randomStudent(ArrayList array){
		Random r = new Random();
		Student s = array.get(r.nextInt(array.size()));
		System.out.println(s.getName());	
	}
	
	
	/*
	 * 定义方法,总览学生信息
	 * 遍历集合
	 */
	public static void printStudent(ArrayList array){
		for(int i = 0; i < array.size() ; i++){
			Student s = array.get(i);
			System.out.println(s.getName()+"\t"+s.getAge());
		}
	}
	
	/*
	 * 定义方法,存储Student对象到集合中
	 */
	public static void addStudent(ArrayList array){
		Student s1 = new Student();
		Student s2 = new Student();
		Student s3 = new Student();
		Student s4 = new Student();
		Student s5 = new Student();
		
		s1.setName("张三1");
		s1.setAge(18);
		
		s2.setName("张三2");
		s2.setAge(19);
		
		s3.setName("张三3");
		s3.setAge(18);
		
		s4.setName("张三4");
		s4.setAge(20);
		
		s5.setName("张三5");
		s5.setAge(17);
		
		array.add(s1);
		array.add(s2);
		array.add(s3);
		array.add(s4);
		array.add(s5);
	}
}

定义一个student类:

package cn.itcast.demo07;
/*
 * 学生类:
 * 	属性 :姓名,年龄
 */
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;
	}
}

输出的结果:

Java 案例八 随机点名系统(使用类实现,面向对象)_第1张图片

你可能感兴趣的:(Java)