如何打印到同一行? [英] How can I print to the same line?

查看:110
本文介绍了如何打印到同一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想像这样打印一个进度条:

I want to print a progress bar like so:

[#                    ] 1%
[##                   ] 10%
[##########           ] 50%

但是这些都应该打印到终端中的同一行而不是新行。
我的意思是每个新行应该替换前一个,它不是关于使用 print()而不是 println()

But these should all be printed to the same line in the terminal instead of a new one. What I mean by that is that each new line should replace the previous, it's not about using print() instead of println().

我怎样才能用Java做到这一点?

How can I do that in Java?

推荐答案

像这样格式化你的字符串:

Format your string like so:

[#                    ] 1%\r

请注意 \ r 字符。这就是所谓的回车,它会将光标移回到行的开头。

Note the \r character. It is the so-called carriage return that will move the cursor back to the beginning of the line.

最后,请确保使用

System.out.print()

而不是

System.out.println()

这篇关于如何打印到同一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆