In this tutorial Console program allow to user only enter numbers.
Variables are defined in the first row. Then users enter char in do-while loop. In the loop “if statement” checks the char whether is number or not.
Source Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
static void Main(string[] args) { double val = 0; string num = ""; Console.Write("Enter Number: "); ConsoleKeyInfo chr; do { chr = Console.ReadKey(true); if (chr.Key != ConsoleKey.Backspace) { bool control = double.TryParse(chr.KeyChar.ToString(), out val); if (control) { num += chr.KeyChar; Console.Write(chr.KeyChar); } } else { if (chr.Key == ConsoleKey.Backspace && num.Length > 0) { num = num.Substring(0, (num.Length - 1)); Console.Write("\b \b"); } } } while (chr.Key != ConsoleKey.Enter); Console.ReadKey(); } |
Output:
You can find more similar examples of programming for this programming language in the site.