Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to print 2 digits for seconds and minutes using printf but I keep getting an error

Tags:

java

printf

I am making a clock in java and I have to print 2 digits for the minutes and 2 digits for the seconds. I am using printf to try to print the two values but I keep receiving an error saying "illegal statement" or "; exprected". What am I doing wrong?

Below is the code that I have attempted to implement and has failed thus far.

public void printStandard() {
    int hours;

    if (hrs < 12) {
        System.out.printf(hrs + ":" + mins + ":" + %2d + "AM", secs);
    } else if (hrs > 12) {
        hours=hrs-12;
        System.out.printf(hours + ":" + mins + ":" + %2d+ "PM"), secs;
    } else if (hrs == 12) {
        System.out.printf(hrs + ":" + mins + ":" + %2d, secs + "PM");
    }
}
like image 243
Sidney Heier Avatar asked Jan 30 '26 02:01

Sidney Heier


2 Answers

public void printStandard(int hrs, int mins, int secs) {
if (hrs < 12) {
    System.out.printf("%02d:%02d:%02d AM%n", hrs, mins, secs);
} else {
    System.out.printf("%02d:%02d:%02d PM%n", hrs - 12, mins, secs);
}

Print two digits.

like image 73
Ars Avatar answered Feb 01 '26 16:02

Ars


The format goes inside the double quotes. Instead of

System.out.printf(hrs + ":" + mins + ":" + %2d + "AM", secs)

I think you wanted something like

System.out.printf("%02d:%02d:%02d AM%n", hrs, mins, secs);

Also, I think you wanted to pass the arguments to your method. And you could use a regular else. Something like,

public void printStandard(int hrs, int mins, int secs) {
    if (hrs < 12) {
        System.out.printf("%02d:%02d:%02d AM%n", hrs, mins, secs);
    } else {
        System.out.printf("%02d:%02d:%02d PM%n", hrs - 12, mins, secs);
    }
}
like image 32
Elliott Frisch Avatar answered Feb 01 '26 15:02

Elliott Frisch