你可以如何在Java中将1显示为01?

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

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 - 十进制数字

来源:官方 Oracle 文档关于格式化数字字符串

英文:

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(&quot;%02d&quot;, num)

Or if you could write something like this:

String text = (num &lt; 10 ? &quot;0&quot; : &quot;&quot;) + num;

huangapple
  • 本文由 发表于 2020年7月28日 18:31:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/63132072.html
匿名

发表评论

匿名网友

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

确定