In this video I perform a check whether a number is an integer or a double.
If it is double, it fills out a List<double>(); and if it is integer, it fills out a List<int>(); Once something is entered, which is neither double nor integer, the loop is broken and the program prints the doubles and the integers in separate lines, putting smiles in front of every number.
At the end of the video I use the debugger, because I tought that my code is not working, as far as I was a little tired to notice that I shold break the loop in order to make it work.
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 34 35 36 37 38 39 40 41 42 43 44 45 46 |
using System; using System.Collections.Generic; class Program { static void Main() { List <int> ints= new List<int>(); List<double> doubles = new List<double>(); while (true) { int intResult; double doubleResult; Console.WriteLine("Please, enter an integer or a double:"); string input = Console.ReadLine(); if (int.TryParse(input, out intResult)) { ints.Add(intResult); } else if (double.TryParse(input, out doubleResult)) { doubles.Add(doubleResult); } else { break; } } Console.Write("You entered {0} ints", ints.Count); foreach (var i in ints) { Console.Write(" :) " + i); } Console.WriteLine(); Console.Write("You have entered {0} doubles:", doubles.Count); foreach (var d in doubles) { Console.Write(" :) " + d); } Console.WriteLine(); } } |
This code can be used as a very good example for the usage of try.parse with combination with conditional operator. Enjoy it!
The application, created with the abovementioned code is here.
The code of the current article is part of the free Bulgarian C# programming book.