java随机点名案例

 

package com.doit.demo03;
/*
1.定义一个学生类Student
2.定义一个测试类RandomList
3.定义方法添加学生
4.定义一个方法遍历查看学生信息
5.定义一个方法生成随机数
 */
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;

public class RandomNameList {
    public static void main(String[] args) {
        ArrayList list=new ArrayList<>();
        addStudent(list);
        System.out.println("----------");
        show(list);
        System.out.println("----------");
        Student s=randomIndex(list);
        System.out.println(s.id+"  "+s.name+",今天答题!!!");
    }

    public static void addStudent(ArrayList list) {
        Scanner sc=new Scanner(System.in);
        for (int i = 0; i < 2; i++) {
            Student s=new Student();
            System.out.println("请输入第"+(i+1)+"个学生的学号:");
            s.id=sc.next();
            System.out.println("请输入第"+(i+1)+"个学生的姓名:");
            s.name=sc.next();
            //将学生添加到集合中
            list.add(s);
        }
    }
    //查看所有学生信息
    public static void show(ArrayList list) {
        for (int i = 0; i < list.size(); i++) {
           Student s=list.get(i);
            System.out.println(s.id+"  "+s.name);
        }
    }
    //生成随机索引
    public static Student randomIndex(ArrayList list) {
        Random r=new Random();
       int index= r.nextInt(list.size());
        Student s= list.get(index);
        return s;
    }

}

你可能感兴趣的:(java,windows,开发语言)