0

How to edit the code so that it won't crash if char or strg was inputted into the console ?

do { Console.Write("x = "); int x = Convert.ToInt32(Console.ReadLine()); Console.Write("y = "); int y = Convert.ToInt32(Console.ReadLine()); int sum = x+y; Console.WriteLine("Result: {0}", sum); } while(true); //courtesy of Sololearn

20th Dec 2016, 4:52 AM
Billy Anak Leo
Billy Anak Leo - avatar
2 Respuestas
0
you can use TryParse function that is return a result of parsing the string if available or not , but without crash string value1 = Console.ReadLine(); int intValue1; bool isParsed = int.TryParse(value1, out intValue1); string value2 = Console.ReadLine(); int intValue2; bool isParsed2 = int.TryParse(value2, out intValue2); if (isParsed== false || isParsed2==false) Console.WriteLine("Only numbers are valid.");
7th Jan 2017, 5:43 AM
Ahmad Hamdan
Ahmad Hamdan - avatar
- 1
Try it: do { Console.Write("x = "); String sx = Console.ReadLine(); Console.Write("y = "); String sy = Console.ReadLine(); if(Regex.IsMatch(sx, @"^\d+
quot;) && Regex.IsMatch(sy, @"^\d+
quot;)) { int x = Convert.ToInt32(sx); int y = Convert.ToInt32(sy); int sum = x+y; Console.WriteLine("Result: {0}", sum); } } while(true);
20th Dec 2016, 6:29 AM
Vagner Lucion
Vagner Lucion - avatar