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)
{
var hoursAsString = Console.ReadLine();
var minutesAsString = Console.ReadLine();
int hours;
int minutes;
bool valid = false;
while (!valid)
{
if (!int.TryParse(hoursAsString, out hours) || !int.TryParse(minutesAsString, out minutes))
{
valid = false;
}
else if (((hours > 23) && (hours < 0)) || ((minutes < 0) && (minutes > 59)))
{
valid = false;
}
else if (string.IsNullOrEmpty(hoursAsString) || (string.IsNullOrEmpty(minutesAsString)))
{
valid = false;
}
else
{
valid = true;
}
if (!valid)
Console.WriteLine("This is not a valid time. Try again!");
hoursAsString = Console.ReadLine();
minutesAsString = Console.ReadLine();
}
if (int.TryParse(hoursAsString, out hours) && int.TryParse(minutesAsString, out minutes))
Console.WriteLine($"The time is {hours}:{minutes}");
}
}
}
It can’t see {minutes} in Console.WriteLine, I can’t get why;) Thanks in advance!
Can anyone please help me to solve it?