如何打印整数 00 而不是 java 打印 0

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19933499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 21:38:52  来源:igfitidea点击:

How to print the integer 00 instead of java printing 0

java

提问by AomSet

I have a variable saying private int minutes = 00.

我有一个变量说private int minutes = 00

If I do System.out.println(minutes), Java will print 0instead of 00, which is the value. It is removing the last zero, but in this particular example, I want it to print 00. How to do that?

如果我这样做System.out.println(minutes),Java 将打印0而不是00,这是值。它正在删除最后一个零,但在这个特定示例中,我希望它打印00. 怎么做?

I also tried making minutes a string, and do: Integer.parseInt(minutes)and then print that. But the result is the same.

我还尝试将分钟变成一个字符串,然后执行:Integer.parseInt(minutes)然后打印出来。但结果是一样的。

回答by Ted Hopp

You can print with a format:

您可以使用以下格式打印:

System.out.printf("%02d%n", minutes);

Explanation:

解释:

  • The %02dspecifies an integer conversion ($d) with a width of 2 and a 0 padding flag.
  • The %nspecifies a line terminator (to mimic the new line that printlnadds)
  • %02d指定的整数变换($d)为2的宽度和0填充标记。
  • %n(即模仿新行指定行终止println加)

If you want to convert minutesto a Stringfor use within the program (rather than printing) you can use String.formatto the same effect:

如果您想转换minutes为 aString以在程序中使用(而不是打印),您可以使用String.format相同的效果:

int minutes = 0;
String sMinutes = String.format("%02d", minutes);

More information can be found in the docs on Formattersyntax.

更多信息可以在关于Formatter语法文档中找到。

回答by arshajii

You can use printf():

您可以使用printf()

int n = 00;
System.out.printf("%02d%n", n);
00

But be careful with prepending int literals with a 0, since that makes them octal(see JLS §3.10.1).

但是要小心在 int 文字前面加上 a 0,因为这会使它们变成八进制(参见JLS §3.10.1)。

For instance,

例如,

int n = 010;
System.out.printf("%02d%n", n);
08

回答by JHS

You can do the following -

您可以执行以下操作 -

private int minutes = 0
DecimalFormat formatter = new DecimalFormat("00");
String aFormatString = formatter.format(minutes);

System.out.println(aFormatString);

Just saving some lines - System.out.println(new DecimalFormat("00").format(minutes));

只是保存一些行 - System.out.println(new DecimalFormat("00").format(minutes));

回答by rafael amorim

you can try this method, i've learned it in the college

你可以试试这个方法,我在大学里学过的

private static String formate(int valor) {
    return (valor < 10 ? "0" : "") + valor;
}