gpt4 book ai didi

java - (Java) 在控制台中逐个字母地打印文本 - ft. Lag

转载 作者:太空宇宙 更新时间:2023-11-04 13:22:49 25 4
gpt4 key购买 nike

所以我正在制作一个只使用 java IDE 中的控制台的游戏,但我在使用延迟时遇到了问题。我的目标是创建一种方法,当通过参数传递文本时,它会逐个字母地打印它,延迟 50。(有点像 Pokemon 系列中的文本,它如何滚动每个字母)。

我遇到的问题是滞后。我正在运行 amd fx-8350 cpu(4GHz,4 核 + 4 虚拟核)。每当我将延迟量更改为 100 毫秒左右或以下时,控制台都会打印半个单词,然后打印另一半的一点点,然后是半个句子,然后可能是一个字符,等等。

我在这里尝试了这段代码(它有效,但有延迟):

public void scroll(String text){
int delay = 50;
ActionListener action = new ActionListener()
{
int counter = text.length();
@Override
public void actionPerformed(ActionEvent event)
{
if(counter == 0)
{
timer.stop();
}
else
{
System.out.print(text.substring(text.length() - counter, ((text.length() - counter) + 1)));
counter--;
}
}
};
timer = new Timer(delay, action);
timer.start();

}//end scroll

这段代码也是如此(也可以工作,具有相同的滞后量):

public void scroll(String text){
for(int i = 0; i <= text.length(); i++){
try {
Thread.sleep(1000);
}catch(InterruptedException ex){
Thread.currentThread().interrupt();
}
System.out.print(text.substring(i, i + 1));
}
}//end scroll

总之,当我尝试延迟线程时,我猜测计算机所做的不仅仅是“延迟”。有什么想法吗?

-谢谢,埃里克

最佳答案

首先,关于您的代码的一些随机注释。这是错误的:

for(int i = 0; i <= text.length(); i++){

无论您是迭代字符串、数组、列表还是其他任何内容,通常的模式始终是

i = 0; i < length; i++

即通过使用<=你得到了一个异常(exception)。这是不需要的:

text.substring(i, i + 1)

第一个例子看起来更糟。您可以使用text.charAr(i) .

<小时/>

我尝试使用此代码作为替代方案:

for(int i = 0; i < text.length(); i++) {
long start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < 50) {

}
System.out.print(text.charAt(i));
}

它在 IntelliJ 中仍然不起作用。然而它和你的代码在终端中工作得很好,所以我认为 IntelliJ 只是不喜欢立即打印。 flush没有什么区别,但它的文档在 OutputStream暗示可能发生的事情:

If the intended destination of this stream is an abstraction provided by the underlying operating system, for example a file, then flushing the stream guarantees only that bytes previously written to the stream are passed to the operating system for writing; it does not guarantee that they are actually written to a physical device such as a disk drive.

再说一次,我认为 IDE 是问题所在,它超出了您的代码的控制范围。

关于java - (Java) 在控制台中逐个字母地打印文本 - ft. Lag,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32918414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com