+ 2

c# do while loop and switch

Hello, I new in c# and I have a little problem. Im using a switch in side a do while loop. I want to protect a user from writing something other that a integer or a int other that between <1,4> I mean something like this: do { int x; // i write here x if () // i got statement that will back me again to write x if i dont put a int or the x is not between <1,4> { } switch (x) { case 1: { } } case 2: { } case 3: { } case 4: { } default: { break; } } } while ();

27th Feb 2018, 11:08 PM
mercin
mercin - avatar
2 Antworten
+ 10
Hi, Mercin! Making sure a user enters a number would require exception handling, which I'm not sure you've reached yet. The range checking can be handled in another do/while loop: do { x = Console.ReadLine(); if (x < 1 || x > 4) Console.WriteLine("Must be between 1 and 4!"); } while (x < 1 || x > 4); By the way, cases and the default don't need braces. If you prefer, you could instead write the error message in the default. The user would have to cycle through again, anyway. Add the condition of x < 1 || x > 4 to the do/while.
28th Feb 2018, 1:45 AM
Tamra
Tamra - avatar
+ 3
Thanks for answer but i needed also a way to protect user from writing a string so i used TryParase metod. It looks something like this : int x; do { bool result = int.TryParse(Console.ReadLine(), out x); switch (x) { case 1: { break; } case 2: { break; } case 3: { break; } default: { if (x == 4) { Console.WriteLine("Thanks for using"); } else { Console.WriteLine("Choose a numer from 1 to 3"); } break; } } } while (x!=4);
28th Feb 2018, 1:58 AM
mercin
mercin - avatar