将一个名为 prescriptionCode 的变量在 Java 中以特定格式显示。

huangapple go评论79阅读模式
英文:

Making a prescriptionCode (variable) appear in specific format in java

问题

抱歉标题可能不太准确,但我无法用其他方式表达这个。假设我有一个变量表示处方的唯一代码。我已经知道总共有400个处方。因此,对于每个新的处方,我希望代码递增一个。第一个我希望是001,第二个是002,依此类推。我知道我可以设置一个静态整数,但如何在前面添加0,以便打印出001,而不仅仅是1呢?我是Java新手,所以我可能在问一个非常愚蠢的问题。谢谢您!

英文:

sorry for the title but couldn't really express this in another way.
So, let's say I have a variable that represents a prescription's unique code. I already know that there a total of 400 prescriptions. So for every new prescription I would like that code to change by one. The first one I want it to be 001, the second one 002 etc. I know I can just set a static int but how can I make the 0's appear in the front so it prints 001 and not just 1? I am new to java so I might be asking a really stupid question. Thanks for your time!

答案1

得分: 0

你可以使用Java格式说明符进行格式化。
以下是执行此操作的代码:

int prescriptionCode = 1;
System.out.println(String.format("%03d", prescriptionCode));

字符串"%03d"是格式说明符。从后向前看,"d"表示您在此处需要的值是十进制的,"3"表示您希望该值的长度为3个字符,无论其实际长度如何,"0"表示您希望使用0来填充数字未占用的剩余空间。

英文:

You can format it with Java format specifiers.
Here would be the code to do that:

int prescriptionCode = 1;
System.out.println(String.format("%03d", prescriptionCode));

The string "%03d" is the format specifier. Going backwards, "d" indicates that the value you want here is a decimal, "3" indicates that you want the value to be 3 characters long regardless of its actual length, "0" means that you want to fill the remaining space the number doesn't take up with 0's.

huangapple
  • 本文由 发表于 2020年4月9日 09:21:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/61112506.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定