思路:首先使用Arrays的asList()方法来存储全部学生姓名,接着把他们全部存储到ArrayList集合中,然后使用Scanner获取从控制台输入的指令,最后使用Random生成随机下标访问ArrayList集合中的数据

 1.存储数据

List<String> list = Arrays.asList("zs","ls","ww","zl","tq");

2.构造一个包含指定 collection 的元素的列表,这些元素是按照该 collection 的迭代器返回它们的顺序排列的

List<String> names = new ArrayList<String>(list);

3.Scanner获取从控制台输入的指令

Scanner scanner = new Scanner(System.in);
String input = scanner.next();

4.使用do{}while()循环产生随机数,通过该随机数来获取到集合中的数据

do{
   if(input.equals("Y") || input.equals("y")){
   int index = random.nextInt(names.size());
   System.out.println(names.get(index));
   input = scanner.next();
  }else{
   System.out.println("已退出点名");
   break;
  }
}while (true);

测试一下

这样发现我们输出的名字会重复,那怎么解决呢?我们只需要在每次输出姓名之后通过ArrayListremove()方法来删除该姓名即可。

do{
   if(input.equals("Y") || input.equals("y")){
   int index = random.nextInt(names.size());
   System.out.println(names.get(index));
   names.remove(index);
   input = scanner.next();
  }else{
   System.out.println("已退出点名");
   break;
  }
}while (true);

 可是当我们再测试的时候我们会发现虽然姓名不会重复了,可是当我们一直点名时会发生异常

原因是当我们把集合中的数据全部remove之后,这时集合的元素数为0,而我们Random中的nextInt传入的参数需要是大于0的,则会报IllegalArgumentException(不合法的参数异常),所以我们循环之前需要判断一下集合中是否有元素,如果没有直接跳出循环

if(names.isEmpty()){
  System.out.println("已全部点名");
  break;
}

这样不重复点名的全部代码就完成了

全部代码:

import java.util.*;

public class Main {
 public static void main(String[] args) {
   Scanner scanner = new Scanner(System.in);
   Random random = new Random();
   List<String> list = Arrays.asList("zs","ls","ww","zl","tq");
   List<String> names = new ArrayList<String>(list);
   System.out.println("开始点名请输入Y/y");
   System.out.println("结束点名请输入任意键");
   String input = scanner.next();
   do{
    if(names.isEmpty()){
       System.out.println("已全部点名");
       break;
     }
     if(input.equals("Y") || input.equals("y")){
       int index = random.nextInt(names.size());
       System.out.println(names.get(index));
       names.remove(index);
       input = scanner.next();
     }else{
       System.out.println("已退出点名");
       break;
     }
    }while (true);
 }
}

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐