user3562575
user3562575

Reputation: 9

How can we make a for loop that happens every amount of time?

import java.util.Scanner;

public class Main {

    public static void main(String[] args){
        Scanner startcommand = new Scanner(System.in);
        System.out.println("Say Start to start game:");
        String command = startcommand.nextLine();

        if(command.equalsIgnoreCase("start")){
            for(int countdown = 10; countdown>0; countdown--){
                System.out.println("Starting game in " + countdown + " seconds");

                if (countdown==1){
                    System.out.println("Game has started");
                }
            }
        }
    }
}

How do I make the for loop occur(Say starting in 1, 2, 3, etc..) every second so the game actually starts in 10 seconds? I know this actually isn't a game. I am just practicing to use a different API.

Upvotes: 0

Views: 87

Answers (2)

import java.util.Scanner;

public class Main {
    public static void main(String[] args){

        Scanner startcommand = new Scanner(System.in);
        System.out.println("Say Start to start game:");
        String command = startcommand.nextLine();
        if(command.equalsIgnoreCase("start")){

            for(int countdown = 10; countdown>0; countdown--){
                System.out.println("Starting game in " + countdown + " seconds");
                Thread.sleep(1000);

                if (countdown==1){
                    System.out.println("Game has started");
                }
            }
        }    
    }
}

You can use Thread.sleep() to do that.. your program will sleep for 1 second on each iteration..

note: (especially to downvoter)
@fe11e was lucky because he can still edit his post within the time limit, so his edit was not recorded.. his first post was using wait(), not using sleep(), then after I posted my answer, he changed his.. now my answer is like a stupid post..

Upvotes: 2

user1544987
user1544987

Reputation:

You can use Thread.sleep(1000), this will cause the main thread to wait 1 second, then continue.

public static void main(String[] args) throws InterruptedException {

Scanner startcommand = new Scanner(System.in);

System.out.println("Say Start to start game:");
String command = startcommand.nextLine();

if(command.equalsIgnoreCase("start")){

    for(int countdown = 10; countdown > 0; countdown--){

        System.out.println("Starting game in " + countdown + " seconds");
        Thread.sleep(1000);  //this line will cause the main thread to pause for 1000 ms or 1 sec
    }


}

Upvotes: 0

Related Questions