写一个完整的可运行的java,随机五个位置,上单,打野,中单,射手,辅助
时间: 2023-10-23 07:08:26 浏览: 95
好的,以下是一个完整可运行的 Java 代码示例,其中包含了两种随机选取五个位置的方法:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class RandomRoles {
public static void main(String[] args) {
ArrayList<String> roles = new ArrayList<>();
roles.add("上单");
roles.add("打野");
roles.add("中单");
roles.add("射手");
roles.add("辅助");
// 方法一:使用 Collections.shuffle() 方法随机排列
Collections.shuffle(roles);
System.out.println("随机出的位置顺序为:" + roles);
// 方法二:使用 java.util.Random 类生成随机数,并移除已选中的角色
Random random = new Random();
System.out.println("随机出的位置顺序为:");
for (int i = 0; i < 5; i++) {
int index = random.nextInt(roles.size());
System.out.println(roles.remove(index));
}
}
}
```
该程序中,我们定义了一个 `ArrayList` 类型的变量 `roles`,存储了五个位置。然后分别使用了两种不同的方法来随机选出五个位置。最后打印出随机出的位置顺序。你可以将上述代码复制到一个名为 `RandomRoles.java` 的文件中,然后在命令行中使用 `javac RandomRoles.java` 命令编译该程序,再使用 `java RandomRoles` 命令运行该程序。
阅读全文
相关推荐















