写一个程序,把这16支球队随机分为4个组。采用List集合和随机数
2008 北京奥运会男足参赛国家:
科特迪瓦,阿根廷,澳大利亚,塞尔维亚,荷兰,尼日利亚、日本,美国,中国,新西 兰,巴西,比利时,韩国,喀麦隆,洪都拉斯,意大利
package src.com.itheima12;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Work01 {
public static void main(String[] args) {
//用于存放国家的集合
List<String> countryList = new ArrayList<>();
//用于存放参赛足球组的集合
List<String> footBellList = new ArrayList<>();
//定义一个boolean类型数组用于标志随机数是否重复 默认值false
boolean[] arr = new boolean[16];
countryList.add("科特迪瓦");
countryList.add("阿根廷");
countryList.add("澳大利亚");
countryList.add("塞尔维亚");
countryList.add("荷兰");
countryList.add("尼日利亚");
countryList.add("日本");
countryList.add("美国");
countryList.add("中国");
countryList.add("新西兰");
countryList.add("巴西");
countryList.add("比利时");
countryList.add("韩国");
countryList.add("喀麦隆");
countryList.add("洪都拉斯");
countryList.add("意大利");
Random random = new Random();
//用于在循环中遍历足球组
int p=0;
//用于装随机索引
int ranIndex = 0;
for (int j = 1;j <= 4;j++){
System.out.println("第"+j+"组:");
for (int i = 0;i < 4;i++){
while (true){
//获取随机索引
ranIndex = random.nextInt(countryList.size());
//判断此索引是否已经随机过 true表示已经随机过
if (arr[ranIndex] == true) {
continue; //continue后将不再执行此循环内之后的语句
}
arr[ranIndex] = true;
footBellList.add(countryList.get(ranIndex));
break;
}
System.out.print(footBellList.get(p++)+" ");
}
System.out.println();
}
}
}
输出结果1:
第1组:
比利时 塞尔维亚 新西兰 喀麦隆
第2组:
巴西 日本 科特迪瓦 中国
第3组:
澳大利亚 洪都拉斯 荷兰 意大利
第4组:
阿根廷 韩国 美国 尼日利亚
输出结果2:
第1组:
意大利 韩国 洪都拉斯 比利时
第2组:
中国 阿根廷 美国 新西兰
第3组:
巴西 喀麦隆 荷兰 科特迪瓦
第4组:
尼日利亚 日本 塞尔维亚 澳大利亚