2

SOLVED: I am currently doing a project to create a clock that works in that when the method tick is called, the clock will increment by 1 second. There are other issues, but right now I am having trouble figuring out why my output is "Clock finally reads: 12:0:0" when I have listed the components as "00." It should be reading 12:00:00. In addition, if the hour were 1, it should output "01" as well.


UPDATE: Error is fixed. However, I also need to implement this so it shows if it is AM or PM. Now currently, it returns this as example (12:00:00false), instead of writing the AM or PM from the boolean. How can I fix this? My tick method is:

public void tick() {

  this.seconds++;

  if (this.seconds == 60) {
      this.seconds = 00;
      this.minutes++;}

  if (this.minutes == 60) {
      this.hours++;
      this.minutes = 00;}

  if(this.seconds == 60){
      this.minutes++; 
      this.seconds = 00; 
      if(this.minutes == 60){
          this.hours++; 
          this.minutes = 00;
      }}

  if(this.hours == 13) {
      this.hours = 1;
      this.morning = false;
  }
  if (this.morning) {
    AMPM = "AM";  
  }
  else {
      AMPM = "PM";  

  }   
  }

and my return method is:

@Override
  public String toString() {
           return String.format("%1d:%02d:%02d%2s", hours, minutes, seconds, morning);


}

What am I doing wrong?


Ally
  • 23
  • 4
  • 4
    In Java `0` prefixed number literal is represented as octal (and additional leading zeros are stripped). In your code `00` = `0` so don't use `00`. – Karol Dowbecki Nov 29 '18 at 17:19
  • 1
    You're outputting `morning` which is a boolean instead of the `AMPM` variable. – Nick Nov 29 '18 at 23:59

1 Answers1

4

Try the method String.format:

@Override
public String toString() {
    return (String.format("%02d:%02d:%02d", hours, minutes, seconds));
}
Robert Kock
  • 5,795
  • 1
  • 12
  • 20