我如何在Java中实现协作? [英] How do I formate in Java ?
本文介绍了我如何在Java中实现协作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请..
我如何在Java中实现协作?
例如C ++中的 setw()
Please ..
How do I formate in Java ??
Such as setw () in C++
推荐答案
NumberFormat是您要搜索的内容:
使用Java格式化 [
NumberFormat is what you are searching for:
Formatting in Java[^]
我通常使用静态方法String.格式().如果您熟悉C printf(),则可以立即使用它,因为它的工作方式相同.
示例:
格式化的字符串= String.format(名称:%-20s年龄:%10d",nameString,ageInt);
在上面的示例中,姓名的宽度将至少为20个字符,年龄的宽度将为10个字符,并在需要时用空格填充. -"字符表示如果nameString的宽度小于20个字符,则我们希望将其保留在左侧.
刚刚尝试可以将%s用于任何类型,java执行到字符串的转换.不过,如果要对整数%09d进行零前缀填充,或者要为浮点数指定精度,则可能要使用%d或%f:%10.3f
I usually use the static method String.format() for that. If you are familiar with the C printf() you can use this immediately because it works the same way.
Example:
String formatted = String.format("name: %-20s age: %10d", nameString, ageInt);
In the above example the width of name will be at least 20 characters and the width of age will be 10 characters, padded with spaces if needed. The ''-'' character means that if the width of nameString is less than 20 characters then we want to aling it to the left side.
Just tried out that you can use %s for any type, java performs the conversion to string. Still, you might want to use %d or %f if you want for example zero prefix padding for integers %09d or want to specify the precision for floats: %10.3f
这篇关于我如何在Java中实现协作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文