import java.util.ArrayList;
import java.util.Scanner;
import java.util.Random;
class Student{
String name;
int age;
}
class Demo{
public static void main(String[] args){
//1.定义一个集合,存储多个Student信息
ArrayList<Student> stuList = new ArrayList<>();
//2.获取学员数量
int count = getStuCount();
//3.填充学员信息
addStudent(stuList,count);
//4.打印学员信息
printStudent(stuList);
//5.随机获取一名学员,
Student stu = randomStudent(stuList);
System.out.println("随机抽取的姓名:" + stu.name + ",年龄:" + stu.age);
}
//定义一个方法,获取用户输入的:学员数量
public static int getStuCount(){
Scanner sc = new Scanner(System.in);
System.out.println("请输入学员数量:");
int count = sc.nextInt();
return count;
}
//定义一个方法,添加学员信息
public static void addStudent(ArrayList<Student> list , int count){
Scanner sc = new Scanner(System.in);
for(int i = 0;i < count ; i++){
System.out.println("请输入第:" + (i + 1) + " 位学员信息:");
System.out.println("姓名:");
String n = sc.next();
System.out.println("年龄:");
int a = sc.nextInt();
//创建Student对象
Student stu = new Student();//stu = 0x2233
stu.name = n;
stu.age = a;
//将stu存储到集合中
list.add(stu);//向集合中添加的是"引用"
}
}
//定义一个方法,打印所有学员
public static void printStudent(ArrayList<Student> stuList){
System.out.println("=========================================");
for(int i = 0;i < stuList.size(); i++){
Student stu = stuList.get(i);
System.out.println(stu.name + "--" + stu.age);
}
System.out.println("=========================================");
}
//定义一个方法,随机抽取一名学员
public static Student randomStudent(ArrayList<Student> stuList){
Random rdm = new Random();
int index = rdm.nextInt(stuList.size());
return stuList.get(index);
}
}
|
|