C# - A Simple Clock Implementation
C# - A Simple Clock Implementation
CODE
using System;
class Program
{
public static void Main(string[] args)
{
Clock c = new Clock(10,5,0);
Console.WriteLine(c.ToString());
c.Tick();
Console.WriteLine(c.ToString());
c.AddSeconds(65);
Console.WriteLine(c.ToString());
c.AddSeconds(3600 * 24);
Console.WriteLine(c.ToString());
}
}
class Clock
{
private int hours;
private int minutes;
private int seconds;
public Clock(int hours, int minutes, int seconds)
{
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
if (hours > 23 || minutes > 59 || seconds > 59 || hours < 0 || minutes < 0 || seconds < 0)
throw new Exception("Please enter a valid time.");
}
public override string ToString()
{
return hours.ToString("00") + ":" + minutes.ToString("00") + ":" + seconds.ToString("00");
}
public void Tick()
{
Console.WriteLine("1 second added...");
seconds++;
if (seconds == 60)
{
seconds = 0;
minutes++;
}
if(minutes == 60)
{
minutes = 0;
hours++;
}
if (hours == 24)
hours = 0;
}
public void AddSeconds(int seconds)
{
Console.WriteLine("{0} second added...", seconds);
int totalSeconds = 0;
int remainingSeconds;
totalSeconds += this.seconds;
totalSeconds += this.minutes * 60;
totalSeconds += this.hours * 3600;
totalSeconds += seconds;
this.hours = totalSeconds / 3600;
remainingSeconds = totalSeconds - (this.hours * 3600);
this.hours = this.hours % 24;
this.minutes = remainingSeconds / 60;
remainingSeconds = remainingSeconds - (this.minutes * 60);
this.seconds = remainingSeconds;
}
}
Comments
Post a Comment