英文:
How can you display 1 as 01 in java?
问题
在Java中使用g.drawString命令时,如何将1显示为01?我已经尝试查找,但不知道应该使用什么术语。
英文:
How can I display 1 as 01 in Java when using the g.drawstring command I have tried to look but I don't know what term I should use.
答案1
得分: 2
你可以这样格式化字符串并显示它:
g.drawString(String.format("%02d", 1));
%02d 用于格式化,其中 02 表示需要时带有前导零的两位数字,d - 十进制数字
英文:
You can format String and display it like this:
g.drawString(String.format("%02d", 1));
%02d is used for formatting, where 02 states for two digits with leading zero as necessary, and d - decimal number
Source: Official Oracle Documentation on formatting numeric strings
答案2
得分: 0
If you want to print a string that contains that number, you can use String.format.
If you write something like String.format("%02d", yourNumber)
, for yourNumber=1
you will obtain the string 01
, so you can use the previous code in a System.out or draw it on the screen.
If you want to use g.drawString
, you can use the following code:
g.drawString(String.format("%02d", yourNumber), x, y)
英文:
If you want to print a string that contains that number, you can use String.format.
If you write something like String.format("%02d", yourNumber)
, for yourNumber=1
you will obtain the string 01
, so you can use the previous code in a System.out or draw it on screen.
If you want to use g.drawstring
, you can use the following code:
g.drawString(String.format("%02d", yourNumber), x, y)
答案3
得分: 0
你可以使用Java的String.format()方法,像这样(推荐)
String.format("%02d", num)
或者你也可以写成这样:
String text = (num < 10 ? "0" : "") + num;
英文:
You could use Java's String.format() method, like this (recommended)
String.format("%02d", num)
Or if you could write something like this:
String text = (num < 10 ? "0" : "") + num;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论