rajeev ranjan
rajeev ranjan

Reputation: 31

How to use String.format in java 8?

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

Upvotes: 0

Views: 31628

Answers (3)

Someone
Someone

Reputation: 1

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.

Upvotes: 0

Mathan
Mathan

Reputation: 7

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.

Upvotes: 1

Jordi Castilla
Jordi Castilla

Reputation: 26961

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.

Upvotes: 6

Related Questions