当前位置:   article > 正文

自动点名器

自动点名器

班级里有N个学生,实现随机点名器

  1. package MyApi.a00test;
  2. import java.util.ArrayList;
  3. import java.util.Collections;
  4. import java.util.Random;
  5. public class Test1 {
  6. public static void main(String[] args) {
  7. ArrayList<String> list=new ArrayList<>();
  8. Collections.addAll(list,"范闲","范建","范统","杜子腾","王俊凯");
  9. //随机点名
  10. //第一种
  11. /* Random r=new Random();
  12. int index=r.nextInt(list.size());
  13. String name= list.get(index);
  14. System.out.println(name);*/
  15. //第二种
  16. Collections.shuffle(list);
  17. String name=list.get(0);
  18. System.out.println(name);
  19. }
  20. }

班级里面有N个学生

要求:70%的概率随机到男生,30%的概率随机到女生

  1. package MyApi.a00test;
  2. import java.util.ArrayList;
  3. import java.util.Collections;
  4. import java.util.Random;
  5. public class Test2 {
  6. public static void main(String[] args) {
  7. ArrayList<Integer> list=new ArrayList<>();
  8. Collections.addAll(list,1,1,1,1,1,1,1);
  9. Collections.addAll(list,0,0,0);
  10. Collections.shuffle(list);
  11. Random r=new Random();
  12. int index = r.nextInt(list.size());
  13. Integer number = list.get(index);
  14. System.out.println(number);
  15. ArrayList<String> boylist=new ArrayList<>();
  16. ArrayList<String> girllist=new ArrayList<>();
  17. Collections.addAll(boylist,"王俊凯","王源","易烊千玺","夏之光","黄俊捷","肖战","王一博");
  18. Collections.addAll(girllist,"杨幂","迪丽热巴","娜扎");
  19. if(number==1){
  20. int boyindex = r.nextInt(boylist.size());
  21. String boyname = boylist.get(boyindex);
  22. System.out.println(boyname);
  23. }
  24. else {
  25. int girlindex = r.nextInt(girllist.size());
  26. String girlname= boylist.get(girlindex);
  27. System.out.println(girlname);
  28. }
  29. }
  30. }

要求:

被点到的学生不会在被点到,但是如果班级中所有的学生都点完了,需要重新开启第二轮点名

  1. package MyApi.a00test;
  2. import java.util.ArrayList;
  3. import java.util.Collections;
  4. import java.util.Random;
  5. public class Test3 {
  6. public static void main(String[] args) {
  7. ArrayList<String> list=new ArrayList<>();
  8. Collections.addAll(list,"王俊凯","王源","易烊千玺","夏之光","黄俊捷","肖战","王一博","杨幂","迪丽热巴","娜扎");
  9. //创建一个临时的集合,用来存储已经被点到名字的学生
  10. ArrayList<String> list2=new ArrayList<>();
  11. for (int i = 0; i < 10; i++) {
  12. int count= list.size();
  13. Random r=new Random();
  14. for (int j = 0; j < count; i++) {
  15. int index = r.nextInt(list.size());
  16. /* String name = list.get(index);
  17. list.remove(name);*/
  18. String name = list.remove(index);
  19. list2.add(name);
  20. System.out.println(name);
  21. }
  22. //此时表示一轮集合已经结束
  23. list.addAll(list2);
  24. list2.clear();
  25. }
  26. }
  27. }

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号