Created
February 12, 2019 19:52
-
-
Save TheBrambleShark/1885b737997fcd7f9e21485e6ccfeb57 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| private static int ReadInt(int min = int.MinValue, int max = int.MaxValue) | |
| { | |
| StringBuilder sb = new StringBuilder(); | |
| do | |
| { | |
| ConsoleKeyInfo key = Console.ReadKey(true); | |
| if (char.IsNumber(key.KeyChar)) | |
| { | |
| Console.Write(key.KeyChar); | |
| sb.Append(key.KeyChar); | |
| } | |
| else if (key.Key == ConsoleKey.Backspace && sb.Length > 0) | |
| { | |
| Console.Write("\b \b"); | |
| sb.Length--; | |
| } | |
| else if (key.Key == ConsoleKey.Enter) | |
| { | |
| if (sb.Length > 0) | |
| { | |
| int num = int.Parse(sb.ToString()); | |
| if (num >= min && num <= max) | |
| { | |
| Console.WriteLine(); | |
| return num; | |
| } | |
| else | |
| { | |
| int line = Console.CursorTop; | |
| int col = Console.CursorLeft; | |
| Console.SetCursorPosition(0, line + 1); | |
| Console.WriteLine($"Input must be between {min} and {max} inclusive"); | |
| Console.SetCursorPosition(col, line); | |
| } | |
| } | |
| } | |
| else | |
| { | |
| Console.Beep(); | |
| } | |
| } while (true); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment