How to use String.format in java 8?

試著忘記壹切 提交于 2019-12-25 17:15:17

问题


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);

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());
    }
}

回答1:


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);

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.




回答2:


A real answer to this problem is only your type int. You don't have to use Object specifically but you have to use a type that inherit from Object and int is a raw type that does not inherit from Object, like all raw types. So you can use Integer instead of int to solve your problem.




回答3:


I know this is old, but I have a guess.

private int hour;
private int second;
private int minute;

As above, you declared hour, second and minute as of int type which is a primitive data type and is not compatible to the Object type.

You might wanna change them to:

private Integer hour;
private Integer second;
private Integer minute;

Integer is a wrapper for the primitive type int and is used to objectify it. By then, the line String.format("%02d:%02d:%02d",hour,minute,second); should work fine.



来源:https://stackoverflow.com/questions/30440073/how-to-use-string-format-in-java-8

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!