Ravin
Ravin

Reputation: 626

Java beginner question - String.format

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

    }

}

Upvotes: 2

Views: 2516

Answers (5)

wjans
wjans

Reputation: 10115

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.

Upvotes: 0

SJuan76
SJuan76

Reputation: 24885

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!

Upvotes: 1

Tom Jefferys
Tom Jefferys

Reputation: 13310

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

Upvotes: 1

Andreas Dolk
Andreas Dolk

Reputation: 114777

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

Upvotes: 4

fyr
fyr

Reputation: 20859

Because you pass 4 parameters and evaluate only 3 in your format.

"%d:%02d:%02d" <- here are only 3 parameters referenced

Upvotes: 6

Related Questions