编写命令行程序模拟游戏组队:
① 每隔1秒有一个玩家进入,并随机加入A或B队。
② 当A、B队人数均达到4人时,倒计时5秒,然后开始游戏。

JavaJava综合问题2
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- 流比 2022-12-26 17:31关注
import java.util.Random; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.CountDownLatch; public class Game { private static int teamASize = 0; private static int teamBSize = 0; private static final int TEAM_SIZE = 4; private static final int COUNTDOWN_SECONDS = 5; public static void main(String[] args) { Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { Random random = new Random(); int team = random.nextInt(2); if (team == 0) { teamASize++; System.out.println("Player joined team A, current team A size: " + teamASize); } else { teamBSize++; System.out.println("Player joined team B, current team B size: " + teamBSize); } if (teamASize == TEAM_SIZE && teamBSize == TEAM_SIZE) { timer.cancel(); CountDownLatch latch = new CountDownLatch(COUNTDOWN_SECONDS); System.out.println("Starting countdown..."); for (int i = COUNTDOWN_SECONDS; i > 0; i--) { latch.countDown(); System.out.println(i + " seconds left"); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Starting game!"); } } } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用