See here is such a situation:

The user enters his local time in parts, the first - an hour, the second - the minute, the third - the second. I wrote it here in this format: Prog Now I want to check what data the user entered, if the hour indicator is less than 0 or greater than or equal to 24, then it is necessary that the loop h = Convert.ToInt32 (Console.ReadLine ()); repeated. wrote a roadmap like this: prog

I did not decide which operator I tried to use if in this way: enter image description here if the if gives out the rub, it usually continues, if it gives out the fols continues with the same entered one. return h; I tried to write it in the if statement but it doesn’t work, and this is obvious, h is out of sight if a. Please tell me what and how.

  • 2
    Read the “cycles” chapter in a C # book. - VladD
  • Read necessarily. - Temo Kvartskhava
  • one
    Replace the question in the picture code as text. - 0xdb
  • one
    You probably need while or do-while - tym32167
  • Used do-while in this way do {Console.WriteLine ("err try again"); } while (h <0 || h> 25); It didn’t work the same way: do {h = Convert.ToInt32 (Console.ReadLine ()); if (h <0 || h> 25) {Console.WriteLine ("err try again"); }} while (h == true); the problem is the same - Temo Kvartskhava

1 answer 1

Use cycles with the condition, and exit from them only when the user finally enters the correct number. For these purposes, you can use the keyword break . Here, in addition, I wrapped everything in try / catch to foresee the situation if the user enters a non-numeric value.

 while (true) { try { h = Convert.ToInt32(Console.ReadLine()); if (h > 0 && h < 24) break; //нас всё устраивает, выходим из while else Console.WriteLine("Wrong number!! Enter again"); } catch (Exception ex) { Console.WriteLine($"error:{ex.Message}!! Enter again"); } } 
  • one
    Instead of catching an exception, int.TryParse could be used. - VladD