Java初学者问题-String.format
当我在另一个类中调用displayTime12hrclock方法时,它拒绝打印AM或PM。我不明白为什么。
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");
}
}
When I call 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");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
因为您传递了 4 个参数,但仅以您的格式计算 3 个参数。
Because you pass 4 parameters and evaluate only 3 in your format.
您将四个参数传递给
format
,但只显示三个。试试这个:You pass four parameters to
format
but display only three. Try this:您的 String.format 缺少 %s。以下应该有效...
Your String.format is missing a %s. The following should work...
在格式中只有 3 个字段 %d,您将 4 个字段传递给它(小时、分钟、秒、AM/PM)。
最后一个被忽略
作为旁注,当您变得更舒服时,请检查
java.util.Date
java.util.日历
java.util.SimpleDateFormat
Java API 很广泛,可能需要一些时间来学习,但可以做很多事情!
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!
您的格式中只有三个值。
尝试将其更改为:
注意最后一个
%s
。您的格式中只有三个引用 (%d
),因此它仅采用指定的前三个参数。通过添加%s
您可以将第四个参数作为字符串包含在内。You only have three values in your format.
Try changing it into this:
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.