It’s pretty frustrating that Josh stopped showing his solutions. Now we have nothing to compare our solution to the ‘ideal’ solution. Could people please review my solution and ideally provide their own, so I can see how others have implemented this solution. Please also feel free to feedback to me on feedbacks, how to make the code clearer and more optimized.
namespace exe1
{
public class StopWatch
{
private TimeSpan _start;
private TimeSpan _stop;
private TimeSpan _started;
private TimeSpan _stopped;
private TimeSpan _difference;
private string? _input;
private bool IsTimerRunning;
public StopWatch()
{
IsTimerRunning = false;
}
public void Interface(string button)
{
_input = button.ToLower();
if (string.IsNullOrEmpty(_input))
{
throw new ArgumentException(nameof(_input));
}
if(_input == "start" && IsTimerRunning == false)
{
IsTimerRunning = true;
_started = StartTimer();
Console.WriteLine("Timer Started.");
}
else if(_input == "stop" && IsTimerRunning == true)
{
IsTimerRunning = false;
_stopped = StopTimer();
Console.WriteLine("Timer Stopped.");
Console.WriteLine("Duration: " + Duration(_started, _stopped));
}
else if(IsTimerRunning)
{
throw new InvalidOperationException(nameof(IsTimerRunning));
}
}
private TimeSpan StartTimer()
{
_start = new TimeSpan(DateTime.Now.Ticks);
return _start;
}
private TimeSpan StopTimer()
{
_stop = new TimeSpan(DateTime.Now.Ticks);
return _stop;
}
private TimeSpan Duration(TimeSpan Start, TimeSpan Stop)
{
_difference = Stop.Subtract(Start);
return _difference;
}
}
}
namespace exe1
{
internal class Program
{
static void Main(string[] args)
{
var timer = new StopWatch();
while (true)
{
Console.WriteLine("Enter the Word \"Start\" to begin timer, and \"Stop\" to stop timer.");
var input = Console.ReadLine();
timer.Interface(input);
}
}
}
}