I've been learning C# for a little over a month. I am working on an exercise where I ask the user to enter a time in a 24-hour clock format and check if it's valid.
That's not important though. My problem is I'm confused about an error. The below code creates an unhandled exception, and says my input string was not in a correct format. It specifies line 22. (The hour variable.)
Now, I've already fixed it, by moving all the variables except userInput inside the try block. But I'm confused why that fixed it. I'm very new, and have tried googling, but honestly don't really know how to even phrase my question.
The complete (pre-fixed) code is below. I appreciate everyone's patience.
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter a time value in the 24-hour time format. (ex. 19:00)");
var userInput = Console.ReadLine();
var userComponents = userInput.Split(':');
var hour = Convert.ToInt32(userComponents[0]);
var minute = Convert.ToInt32(userComponents[1]);
if (String.IsNullOrWhiteSpace(userInput))
{
Console.WriteLine("Invalid Time");
return;
}
try
{
if (hour <= 23 && hour >= 00 && minute >= 0 && minute <= 59)
Console.WriteLine("Ok");
else
Console.WriteLine("Invalid Time");
}
catch(Exception)
{
Console.WriteLine("Invalid Time");
}
}
}
}
Someone requested I post the fixed code:
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter a time value in the 24-hour time format. (ex. 19:00)");
var userInput = Console.ReadLine();
if (String.IsNullOrWhiteSpace(userInput))
{
Console.WriteLine("Invalid Time");
return;
}
try
{
var userComponents = userInput.Split(':');
var hour = Convert.ToInt32(userComponents[0]);
var minute = Convert.ToInt32(userComponents[1]);
if (hour <= 23 && hour >= 00 && minute >= 0 && minute <= 59)
Console.WriteLine("Ok");
else
Console.WriteLine("Invalid Time");
}
catch(Exception)
{
Console.WriteLine("Invalid Time");
}
}
}
}
Someone also requested the debugger info:
System.IndexOutOfRangeException HResult=0x80131508 Message=Index was outside the bounds of the array. Source=Section 6 24 Hour Time
StackTrace: at Section_6_24_Hour_Time.Program.Main(String[] args) in D:\Repos\Mosh C# Udemy\Exercises\C# Fundamental Exercises\Section 6 24 Hour Time\Section 6 24 Hour Time\Program.cs:line 23