java学习21-简单随机点名器(ArrayList集合)实现

续java学习20https://blog.csdn.net/qq_40790831/article/details/86516808

案例:随机点名器

  • 存储全班同学信息(学号,姓名,年龄)
  • 打印全班同学姓名
  • 在班级总人数范围内,随机产生一个随机数,查找随机数所对应的同学信息(学号、姓名、年龄)
  • 随机点名器明确分为了三个功能,采用ArrayList集合来解决多个学生信息存储问题

CallArrayListDemo类:程序main方法

// 导包
import java.util.Random ;
import java.util.ArrayList;
public class CallArrayListDemo {
	
	public static void main ( String [] args ) {
		
		ArrayList<CallStudent> stuInfos = getStudentInfo() ;
		
		// 打印输出所有学生姓名
		for ( CallStudent c : stuInfos ) {
			
			System.out.print( c.getName() + "\t" ) ;
		}
		
		int index = new Random().nextInt( stuInfos.size() ) ;
		
		System.out.println( "\n恭喜" + stuInfos.get( index ).getName() + ",你被点中了,你的学号是" + stuInfos.get( index ).getSchoolNum() + ",你的年龄是" + stuInfos.get( index ).getAge() ) ; 
	}
	
	/*
		班级学生班级学生信息生成
	*/
	public static ArrayList<CallStudent> getStudentInfo() {
		ArrayList<CallStudent> stuInfos = new ArrayList<CallStudent>() ;
		
		for ( int i = 0 ; i < 27 ; i ++ ) {
			
			stuInfos.add( new CallStudent( "152012" + i , "王" + i , 18 + i ) ) ;
		}
		
		return stuInfos == null ? null : stuInfos;
	}
}

CallStudent类:程序学生对象实体类

public class CallStudent {
	
	// 学号属性
	String schoolNum ;
	
	// 姓名属性
	String name ; 
	
	// 年龄属性
	int age ;
	
	// 构造函数
	public CallStudent( String schoolNum , String name , int age  ) {
		
		this.schoolNum = schoolNum ; 
		this.name = name ;
		this.age = age > 24 ? 24 : age ; 
	}
	
	// get方法,用于返回属性值
	public String getSchoolNum() { return this.schoolNum ; }
	public String getName() { return this.name ; }
	public int getAge() { return this.age ; }
}

猜你喜欢

转载自blog.csdn.net/qq_40790831/article/details/86516823
今日推荐