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");
}
}
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With