2

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

    }

}

5 Answers 5

6

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

"%d:%02d:%02d" <- here are only 3 parameters referenced
Sign up to request clarification or add additional context in comments.

Comments

4

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

1 Comment

@Ravin - if we have too few arguments, then we get a MissingFormatArgumentException at run time. With too many arguments we have to find the bug manually (didn't know that actually, so thanks for the question :D )
1

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

Comments

1

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!

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.