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

eniesee :

I try to simulate a football game in Android Studio (language: Java). I generate 90 random numbers. Each iteration must represent one minute of the match. (But it is now only one second when testing). After every played minute (in this case second), the minutes played and possibly the score must be adjusted in the app. I have already tested a number of solutions that I could find on the internet, such as the Thread solution that appears everywhere. However, this does not result in the result I expected.

Expected output: An app that starts at 0 minutes and a 0-0 score, increasing the number of play minutes by 1 every second, and also adjusting the score if a goal is scored.

Actual output: A white screen for the number of milliseconds specified in the code, and then only the 'final result' of the game. For example: 90' 2-1.

I've already tried to put the try/catch code elsewhere in the loop. I have also replaced sleep with wait. This always produces the same output. Can anyone tell me how I can get the number of seconds to go up live on the screen and the score changes as soon as a goal falls?

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);
            }
        }
    }
}

The playMinute function:

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

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

    return random;
}
appersiano :

Do not use Thread.sleep() is a bad practise. You can use a Countdown Timer and on onTick run your playMinute()

new CountDownTimer(30000, 1000) {

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

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=299763&siteId=1