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");
}
}
}
}
}
如何让for循环发生(比如说,从1,2,3等开始),这样游戏实际上会在10秒内开始?我知道这实际上不是一场比赛。我只是练习使用不同的API。
答案 0 :(得分: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");
}
}
}
}
}
您可以使用Thread.sleep()
来执行此操作..您的程序将在每次迭代时睡眠 1秒钟。
注意:的
(特别是对downvoter)
@ fe11e很幸运,因为他仍然可以在限定时间内编辑他的帖子,所以他的编辑没有记录..他的第一篇文章是使用wait(),而不是使用sleep(),然后在我发布我的答案后,他改变了他的..现在我的回答就像一个愚蠢的帖子..
答案 1 :(得分:0)
你可以使用Thread.sleep(1000),这将导致主线程等待1秒,然后继续。
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
}
}