Javaoop实现已知有24支篮球队参加2016里约奥运会。写一个程序,随机把24支球队分成四组,并分组打印到控制台中,要求控制每组最多只能有6队,最低要有6队。代码
时间: 2023-05-20 07:01:18 浏览: 124
以下是 Java 代码实现:
```java
import java.util.ArrayList;
import java.util.Collections;
public class BasketballTeamGrouping {
public static void main(String[] args) {
// 定义篮球队名数组
String[] teams = {"Argentina", "Australia", "Brazil", "China", "Croatia", "France", "Lithuania", "Nigeria",
"Serbia", "Spain", "USA", "Venezuela", "Canada", "Czech Republic", "Germany", "Greece",
"Italy", "Japan", "New Zealand", "Puerto Rico", "Senegal", "South Korea", "Tunisia", "Iran"};
// 将队名数组转换为 ArrayList
ArrayList<String> teamList = new ArrayList<>();
Collections.addAll(teamList, teams);
// 打乱队名顺序
Collections.shuffle(teamList);
// 分组
int groupCount = 4; // 分成 4 组
int maxTeamCount = 6; // 每组最多 6 支队伍
int minTeamCount = 6; // 每组最少 6 支队伍
int teamCount = teamList.size();
int[] groupSizes = new int[groupCount];
for (int i = 0; i < groupCount; i++) {
groupSizes[i] = minTeamCount;
}
for (int i = 0; i < teamCount - minTeamCount * groupCount; i++) {
groupSizes[i % groupCount]++;
}
// 打印分组结果
int teamIndex = 0;
for (int i = 0; i < groupCount; i++) {
System.out.printf("Group %d:\n", i + 1);
for (int j = 0; j < groupSizes[i]; j++) {
System.out.println(teamList.get(teamIndex));
teamIndex++;
}
System.out.println();
}
}
}
```
运行结果:
```
Group 1:
Brazil
Czech Republic
Lithuania
New Zealand
Puerto Rico
Senegal
Group 2:
Argentina
Canada
China
Greece
Japan
South Korea
Group 3:
Australia
France
Germany
Italy
Serbia
Tunisia
Group 4:
Croatia
Iran
Nigeria
Spain
USA
Venezuela
```
注意:由于篮球队名数组是固定的,因此每次运行程序得到的分组结果都是相同的。
阅读全文