¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita0
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
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.");
- 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);