如何在Java中使用String.format()? [英] How to use String.format() in Java?
问题描述
pre code $ 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); ((m> = 0& m< 60)m:0);
秒=((s> = 0& s< 60)s:0);
public String toMilitary(){
return String.format(%02d:%02d:%02d,hour,minute,second);
$ b因此他所做的是做某种军事时间类和使用字符串格式。所以我问的是,如果有人可以向我解释String.format()是如何工作的,以及上面的格式是如何工作的。感谢您的帮助!
它和C的printf()一样。
%s - >字符串
%d - > int
%f - > float
提前
String.format(%02d,8)
- > OUTPUT:08
String.format(%02d,10)
$>
String.format(%04d,10)
- > OUTPUT:0010
所以基本上它会填充0表达式之前的0的数字,作为第二个参数给出的变量或原始类型,0将被填充以使得所有数字都满足格式方法的第一个参数字符串API。
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:
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!
It works same as printf() of C.
%s -> String
%d -> int
%f -> float
ahead
String.format("%02d", 8)
-> OUTPUT: 08
String.format("%02d", 10)
-> OUTPUT: 10
String.format("%04d", 10)
-> OUTPUT: 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.
这篇关于如何在Java中使用String.format()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!