Java beginner question - String.format
When I call开发者_JS百科 the displayTime12hrclock method in another class, it refuses to print out AM or PM. I can't work out why.
public class Tuna {
private int hour;
private int minute;
private int second;
public void setTime(int h, int m, int s){
hour = h;
minute = m;
second = s;
hour = ((h>= 0 && h <=24 ? h:0));
minute = ((m>= 0 && m <=60 ? m:0));
second = ((s>= 0 && s <=60 ? s:0));
}
public String displayTime(){
return String.format("%02d:%02d:%02d", hour,minute,second);
}
public String displayTime12hrclock(){
return String.format("%d:%02d:%02d", ((hour==0 || hour ==12)?12:hour%12), minute, second, (hour >=12)? "AM":"PM");
}
}
Because you pass 4 parameters and evaluate only 3 in your format.
"%d:%02d:%02d" <- here are only 3 parameters referenced
You pass four parameters to format
but display only three. Try this:
return String.format("%d:%02d:%02d %s", ((hour==0 || hour ==12)?12:hour%12), minute, second, (hour >=12)? "AM":"PM");
Your String.format is missing a %s. The following should work...
String.format("%d:%02d:%02d %s", ((hour==0 || hour ==12)?12:hour%12), minute, second, (hour >=12)? "AM":"PM");
In the format there are only 3 fields %d, you pass 4 to it (hour, minute, second, AM/PM).
The last one is ignored
As a side note, when you get more confortable, check
java.util.Date java.util.Calendar java.util.SimpleDateFormat
Java API is extensive and may take a time to learn, but does a lot of things!
You only have three values in your format.
Try changing it into this:
String.format("%d:%02d:%02d %s", ((hour==0 || hour ==12)?12:hour%12), minute, second, (hour >=12)? "AM":"PM");
Note the last %s
. You only had three references (%d
) in your format, so it was only taking the first three arguments specified. By adding %s
you include the forth argument as a string.
精彩评论