0

I am trying to make a Clock that displays in 24 hour time, like 00:00:00. I've created the ReadTime method in my clock class. In my MainClass I assumed that if I called the ReadTime method in a while loop, that it would increase. However the output just stays at 0:0:0.

public class Clock
{
    Counter _seconds;
    Counter _minutes;
    Counter _hours;

    public Clock()
    {
        _seconds = new Counter("Seconds");
        _minutes = new Counter("Minutes");
        _hours = new Counter("Hours");
    }


    public void Tick()
    {
        _seconds.Increment();
        if(_seconds.Count>=60)
        {
            _minutes.Increment();
            _seconds.Reset();
        }

        if(_minutes.Count >= 60)
        {
            _minutes.Reset();
            _hours.Increment();
        }

        if(_hours.Count >= 24)
        {
            Reset();

        }
    }

    public void Reset()
    {
        _hours.Reset();
        _minutes.Reset();
        _seconds.Reset();
    }

    public void ReadTime()
    {
        string ss = _seconds.Count.ToString();
        string mm = _minutes.Count.ToString();
        string hh = _hours.Count.ToString();

        Console.WriteLine("{0:00}:{0:00}:{0:00}", hh, mm, ss);
    }
}

This is my main method.

public static void Main(string[] args)
    {
        Clock ClockDemo = new Clock();
        while(true)
        {
            ClockDemo.Tick();
            ClockDemo.ReadTime();
            Console.ReadLine();

        }

    }
Dale K
  • 25,246
  • 15
  • 42
  • 71
penfew
  • 55
  • 4
  • 1
    If you try debugging the `ReadTime()` method and inspecting the values, you'll probably see that they actually are incrementing and that the issue is with the formatting of your string – devNull Apr 08 '20 at 01:44
  • You may also want to share the code of the Counter class? I don't think that this is a .net framework class. – Jack Apr 08 '20 at 02:15
  • Do this https://stackoverflow.com/a/888569/1704458 – T.S. Apr 08 '20 at 02:23

1 Answers1

1

The reason this is happening is you already formatted your string before you put it in your custom formatting.

    string ss = _seconds.Count.ToString(); // 0 becomes "0"
    string mm = _minutes.Count.ToString();
    string hh = _hours.Count.ToString();

    Console.WriteLine("{0:00}:{0:00}:{0:00}", hh, mm, ss);

It is not going to pad zeros to a string, only to an int. So instead, try the following:

    string ss = _seconds.Count.ToString("00"); // 0 becomes "00"
    string mm = _minutes.Count.ToString("00");
    string hh = _hours.Count.ToString("00");

    Console.WriteLine("{0}:{1}:{2}", hh, mm, ss);

You can also skip putting them in temporary string variables:

    Console.WriteLine("{0:00}:{1:00}:{2:00}", _hours.Count, _minutes.Count, _seconds.Count);

Or use interpolated string:

    Console.WriteLine($"{_hours.Count:00}:{_minutes.Count:00}:{_seconds.Count:00}");
Chronicle
  • 1,565
  • 3
  • 22
  • 28