使用Map集合 将每个学生对应一个key值
再利用 随机数 生成 最大范围为学生数的一个随机数
在通过 Map集合的 key值 找到key值对应的学生名
最后通过 get 方法打印对应的随机学生。
public class RandomPeople {
public static void main(String[] args) {
HashMap<Integer,String> peopleMap = (HashMap<Integer, String>) peopleMap();
Set<Integer> keys = peopleMap.keySet();
Random r = new Random();
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("=====随机点名系统=====");
System.out.println("1.开始随机 2.退出系统");
System.out.println("请输入功能编号:");
int num = sc.nextInt();
if (num == 1) {
System.out.println("随机一个同学回答问题:");
int i = r.nextInt(peopleMap.size())+1;
System.out.println(peopleMap.get(i));
}else if (num == 2){
return;
}else {
System.out.println("==输入功能编号有误,请重新输入!!==");
}
}
}
public static Map<Integer,String> peopleMap(){
String[] names = {"张三","李四","赵五","刘六","宋七","王八"};
HashMap<Integer,String> peopleMap = new HashMap<Integer,String>();
int num = 1;
for (String v:names) {
peopleMap.put(num++,v);
}
return peopleMap;
}