Hello, I’m working on this task:
Write a program that reads a time from the console. Time is represented by two integers – hours and minutes. Each of them will be written from a new line, hours first. The hour must be a value between 0 and 23, and the minutes between 0 and 59. If the user inputs an incorrect value for either variable, the progarm should output: “This is not a valid time. Try again!”, otherwise: “The time is {hours}:{minutes}” The program should continue to ask for and read values for the hours and minutes until the user inputs valid values for both of them. For example:
>23
>
This is not a valid time. Try again!
>12
>ghgh
This is not a valid time. Try again!
>25
>70
This is not a valid time. Try again!
>5
>17
The time is 5:17
Here is my code:
namespace InputValidation
{
class WhatTimeIsItNow
{
static void Main(string[] args)
{
bool keep = true;
var hoursAsString = Console.ReadLine();
var minutesAsString = Console.ReadLine();
int hours;
int minutes;
while (keep) {
if ((!string.IsNullOrEmpty(hoursAsString)) || (!string.IsNullOrEmpty(minutesAsString))) {
if ((!int.TryParse(hoursAsString, out hours)) || (!int.TryParse(minutesAsString, out minutes))) {
Console.WriteLine("This is not a valid time. Try again!");
hoursAsString = Console.ReadLine();
minutesAsString = Console.ReadLine();
} else if ((minutes < 0 || minutes > 59) && (hours < 0 || hours > 23)) {
Console.WriteLine("This is not a valid time. Try again!");
hoursAsString = Console.ReadLine();
minutesAsString = Console.ReadLine();
} else {
keep = false;
}
} else {
Console.WriteLine("This is not a valid time. Try again!");
hoursAsString = Console.ReadLine();
minutesAsString = Console.ReadLine();
}
}
Console.WriteLine($"The time is {hoursAsString}:{minutesAsString}");
}
}
}
CS0165: Use of unassigned local variable ‘hours’
CS0165: Use of unassigned local variable ‘minutes’
Can anyone please help me to solve it?