如何在java 8中使用String.format? [英] How to use String.format in java 8?
问题描述
今天我在java 8的eclipse Kepler中编写了一个简单的程序。实际上,我从一些视频教程中复制了它。在该教程中,它运行,但在我的计算机中它没有。错误行是
Today I wrote a simple program in eclipse Kepler in java 8. Actually, I copied it from some video tutorial. In that tutorial, it ran, but in my computer it didn't. Error line is
String.format("%02d:%02d:%02d",hour,minute,second);
我不明白这里的错误是什么。
它突出显示类型 String
中的方法 format(String,object [])
不适用于参数(String,int,int,int)
I don't understand what the error is here.
It highlights the method format(String,object[])
in the type String
are not applicable for the argument(String, int, int, int)
public class Demo {
private int hour;
private int second;
private int minute;
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 railwayTime(){
return String.format("%02d:%02d:%02d",hour,minute,second);//error in this line
}
public String regular(){
return String.format("%02d:%02d:%02d %s",((hour==0 ||hour==24)?12:(hour%12)), minute, second, (hour>=12)?"AM":"PM");//error in this line
}
}
public class ShowTime {
public static void main(String[] args){
Demo d=new Demo();
System.out.println(d.railwayTime());
System.out.println(d.regular());
}
}
推荐答案
异常要求您输入数组而不是逗号分隔字符串:
The exception asks you for an array instead comma-sepparated strings:
// incorrect
String.format("%02d:%02d:%02d",hour,minute,second);
// fast but correct
Object[] data = { hour, minute, second };
String.format("%02d:%02d:%02d", data);
但实际上,方法 format(String,object [])
在 String
中不存在,它是: format(String pattern,Object ... arguments)
什么应该用逗号,
。您的语法有些内容,但在显示的代码中没有。
But actually, method format(String,object[])
does not exists in String
, it is: format(String pattern, Object... arguments)
what should work with commas ,
. There is something with your syntax, but not in the shown code.
这篇关于如何在java 8中使用String.format?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!