英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论