如何在每次 while/for 循环迭代后等待一秒钟?

How to wait a second after each while/for loop iteration?

我尝试在 Android Studio 中模拟一场足球比赛(语言:Java)。我生成 90 个随机数。每次迭代必须代表比赛的一分钟。 (但现在测试时只有一秒)。每玩一分钟(在本例中为第二分钟)后,必须在应用程序中调整播放分钟数和可能的比分。我已经测试了很多网上能找到的方案,比如随处可见的Thread方案。然而,这并没有达到我预期的结果。

预期输出:一个从 0 分钟和 0-0 比分开始的应用程序,每秒增加 1 分钟的播放时间,如果进球也会调整比分。

实际输出:代码中指定的毫秒数的白屏,然后只有游戏的'final result'。例如:90' 2-1.

我已经尝试将 try/catch 代码放在循环的其他地方。我还将 sleep 替换为 wait。这总是产生相同的输出。任何人都可以告诉我如何获得在屏幕上直播的秒数,并且得分会在进球后立即改变吗?

public void playLeagueMatch(Team team1, Team team2, TextView minuteTV,
                            TextView homeGoalsTV, TextView awayGoalsTV){

    int strength1 = team1.strength;
    int strength2 = team2.strength;
    int minutesPlayed = 0;
    double separation = Double.valueOf(strength1) / (Double.valueOf(strength1)+Double.valueOf(strength2)) * 100;

    int homeGoals = 0;
    int awayGoals = 0;

    for (minutesPlayed = 0; minutesPlayed < 91; minutesPlayed++) {
        String minuteName = Integer.toString(minutesPlayed);
        minuteTV.setText(minuteName + "'");

        int random = playMinute();

        if(random < 101){
            if(random <= separation){
                homeGoals++;
                homeGoalsTV.setText(Integer.toString(homeGoals));
            }
            else{
                awayGoals++;
                awayGoalsTV.setText(Integer.toString(awayGoals));
            }
            try{
                Thread.sleep(1000);
            }
            catch(InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

playMinute函数:

public int playMinute(){
    Random ran = new Random();

    int random = ran.nextInt(3500) + 1;

    return random;
}

Thread.sleep(1000) 只会休眠 1 秒,因为 1 秒是 1000 毫秒。

一分钟换成Thread.sleep(1 * 60 * 1000)

不要使用 Thread.sleep() 是一种不好的做法。 您可以使用 Countdown TimeronTick 运行 您的 playMinute()

new CountDownTimer(30000, 1000) {

    public void onTick(long millisUntilFinished) {
      Log.i("seconds remaining: " ,""+ millisUntilFinished / 1000);
    }

    public void onFinish() {
         Log.i("Timer Finished");
    }  
}.start();