0

I want to go back to the "Console.Write(num1), if use input the wrong value. how to code? Pls help!

using System; namespace ConsoleApp1 { class Program { static void Main(string[] args) { do { Console.Write("num1 : "); string str = Console.ReadLine(); if (str == "exit") break; int num1; try { num1 = Convert.ToInt32(str); } // I want to go back to start after catch {}, how to do. catch { Console.WriteLine("You are keying in the wrong value, Please Try Again"); num1 = 0; } Console.Write("num2 :"); int mum2 = Convert.ToInt32(Console.ReadLine()); //sum of num1 and mum2 int sum = num1 + mum2; Console.WriteLine("Result: {0}" ,sum); Console.WriteLine("\nThat is amazing"); Console.Read(); } while (true); } } }

25th Mar 2019, 12:15 PM
Kyaw Myo Oo
Kyaw Myo Oo - avatar
5 Answers
+ 2
You can add 'continue' as the last statement in the catch clause and you will go back to the start of the do...while loop. Instead of using try...catch for checking if input is integer number you can use int.TryParse method.
25th Mar 2019, 4:39 PM
gambler
+ 1
Thank you for help
25th Mar 2019, 9:29 PM
Kyaw Myo Oo
Kyaw Myo Oo - avatar
+ 1
To achieve that you could do something like this: using System; namespace ConsoleApp1 { class Program { static void Main(string[] args) { string wrongInputInfo = "You are keying in the wrong value, Please Try Again"; bool exit = false; do { Console.Write("num1: "); string str = Console.ReadLine(); int num1; while (!int.TryParse(str, out num1)) { if (IsExit(str)) { exit = true; break; } Console.WriteLine(wrongInputInfo); Console.Write("num1: "); str = Console.ReadLine(); } if (exit) break; Console.Write("num2: "); int num2; str = Console.ReadLine(); while (!int.TryParse(str, out num2)) { if (IsExit(str)) { exit = true; break; } Console.WriteLine(wrongInputInfo); Console.Write("num2: "); str = Console.ReadLine(); } if (exit) break; //sum of num1 and mum2 int sum = num1 + num2; Console.WriteLine("Result: {0}", sum); Console.WriteLine("\nThat is amazing"); Console.ReadLine(); } while (true); } static bool IsExit(string input) { if (input == "exit") return true; return false; } } }
26th Mar 2019, 2:21 PM
gambler
0
Can you please write some sample code for Try.Parse() Method? If user inputs wrong in num2, I want to go back to "Console.Write("num2 : "). How to code. Thanks!
26th Mar 2019, 1:00 PM
Kyaw Myo Oo
Kyaw Myo Oo - avatar
0
Thanks you so much.
26th Mar 2019, 9:32 PM
Kyaw Myo Oo
Kyaw Myo Oo - avatar