简体   繁体   English

如何在java中同一行打印字符串War Games样式一个字母

[英]How to print string War Games style one letter at time on same line in java

using this code at the minute which I found on the net 在我在网上找到的那一刻使用这段代码

 String welcome = "Would you like to play a game?";
 for (int i = 0; i < welcome.length(); i++) {
      System.out.println(welcome.charAt(i));

    }

Pretty basic stuff, but it prints out really quickly and line by line, how can i add a small pause, and print immediately after the previous character? 非常基本的东西,但是它可以非常快速地逐行打印出来,如何添加一个小暂停,并在前一个字符后立即打印? So by the end it just says Would you like to play a game? 所以到最后它只是说你想玩游戏吗?

Im working in CMD, and Sublime text. 我在CMD和Sublime文本工作。

Thanks! 谢谢!

Use System.out.print instead of println. 使用System.out.print而不是println。 Use Thread.sleep to pause. 使用Thread.sleep暂停。 Loop until the whole string is printed out. 循环直到整个字符串打印出来。

String welcome = "Would you like to play a game?";
for (int i = 0; i < welcome.length(); i++) {
    System.out.print(welcome.charAt(i));
    Thread.sleep(1000L); // in milliseconds
}
System.out.println(); // start a new line

Thread.sleep throws InterruptedException. Thread.sleep抛出InterruptedException。 If this code goes in your main method, the easiest way to handle it (assuming you have no interest in canceling the thread by interrupting it) is to add throws InterruptedException to the main method declaration (the exception will not get thrown, you're just keeping the compiler happy). 如果这个代码进入你的main方法,处理它的最简单的方法(假设你没有兴趣通过中断来取消线程)是向主方法声明添加throws InterruptedException (异常不会被抛出,你是只是保持编译器的快乐)。

Use System.out.print instead of System.out.println . 使用System.out.print而不是System.out.println To add a small delay the easiest thing is to use Thread.sleep . 要添加一个小延迟,最简单的方法是使用Thread.sleep

 for (int i = 0; i < welcome.length(); i++) {
      System.out.print(welcome.charAt(i));
      Thread.sleep(100);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM