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

问题描述 投票:0回答:1

我尝试在Android Studio中模拟足球比赛(语言:Java)。我生成90个随机数。每次迭代必须代表比赛的一分钟。 (但是现在测试时只有一秒钟)。在每分钟播放一次(在本例中为秒)之后,必须在应用程序中调整播放的分钟以及可能的比分。我已经测试了许多可以在Internet上找到的解决方案,例如随处可见的Thread解决方案。但是,这不会导致我预期的结果。

预期输出:一个应用程序,该应用程序从0分钟开始,得分为0-0,每秒将播放分钟数增加1,并且如果进球就可以调整得分。

实际输出:白屏显示代码中指定的毫秒数,然后仅显示游戏的“最终结果”。例如: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;
}
java android android-studio wait sleep
1个回答
-1
投票

[Thread.sleep(1000)将仅睡眠1秒钟,因为1秒钟为1000毫秒。

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

© www.soinside.com 2019 - 2024. All rights reserved.