如何在 Java 中使用 String.format()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22416578/
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
How to use String.format() in Java?
提问by Lemmy301
I am a beginner in Java, and I'm using thenewboston's java tutorials (youtube). At tutorial 36-37 he starts using a String.format(); which he didn't explain in past tutorials. Here is the code for a class he was making:
我是 Java 的初学者,我正在使用 newboston 的 Java 教程 (youtube)。在教程 36-37,他开始使用 String.format(); 他在过去的教程中没有解释。这是他正在制作的课程的代码:
public class tuna {
private int hour;
private int minute;
private int second;
public void setTime(int h, int m, int s){
hour = ((h >= 0 && h < 24) ? h : 0);
minute = ((m >= 0 && m < 60) ? m : 0);
second = ((s >= 0 && s < 60) ? s : 0);
}
public String toMilitary(){
return String.format("%02d:%02d:%02d", hour, minute, second);
}
}
So what he's doing is he's doing some sort of military time class and using String formatting. So what I'm asking is if someone can explain to me how String.format() works and how the formatting above works. Thanks for the help!
所以他正在做的是他正在做某种军事时间课程并使用字符串格式。所以我要问的是是否有人可以向我解释 String.format() 是如何工作的以及上面的格式是如何工作的。谢谢您的帮助!
采纳答案by Hiren
It works same as printf() of C.
它的工作原理与 C 的 printf() 相同。
%s for String
%d for int
%f for float
ahead
先
String.format("%02d", 8)
String.format("%02d", 8)
OUTPUT: 08
输出: 08
String.format("%02d", 10)
String.format("%02d", 10)
OUTPUT: 10
输出: 10
String.format("%04d", 10)
String.format("%04d", 10)
OUTPUT: 0010
输出: 0010
so basically, it will pad number of 0's ahead of the expression, variable or primitive type given as the second argument, the 0's will be padded in such a way that all digits satisfies the first argument of format method of String API.
所以基本上,它会在作为第二个参数给出的表达式、变量或原始类型之前填充 0 的数量,0 将以所有数字满足 String API 格式方法的第一个参数的方式填充。
回答by placeofm
It just takes the variables hour
, minute
, and second
and bring it the the format 05:23:42. Maybe another example would be this:
它只需要变量hour
, minute
,second
并将其设为 05:23:42 格式。也许另一个例子是这样的:
String s = String.format("Hello %s answered your question", "placeofm");
When you print the string to show it in the console it would look like this
当您打印字符串以在控制台中显示它时,它看起来像这样
System.out.println(s);
Hello placeofm answered your question
你好 placeofm 回答了你的问题
The placeholder %02d
is for a decimal number with two digits. %s
is for a String like my name in the sample above. If you want to learn Java you have to read the docs. Here it is for the String
class. You can find the format method with a nice explanation. To read this docs is really important not even in Java.
占位符%02d
用于具有两位数的十进制数。%s
用于像上面示例中我的名字一样的字符串。如果你想学习 Java,你必须阅读文档。这是给String
班级的。您可以找到带有很好解释的格式方法。阅读此文档非常重要,即使在 Java 中也不行。