Below is a code of project that I\'m working on, it\'s just a multiplication cal
ID: 3542501 • Letter: B
Question
Below is a code of project that I'm working on, it's just a multiplication calcultor in console application. The program runs fine, but I'm required one more step that I've no idea how to do which is:
(C)
In your project, you must confirm (validate) that the user
Below is a code of project that I'm working on, it's just a multiplication calcultor in console application. The program runs fine, but I'm required one more step that I've no idea how to do which is: In your project, you must confirm (validate) that the user's input for the first and second number are actually numbers and not letters sentences. Usually, if you use Int32 or other numerical function, the program will terminate itself if the input is not within the limits of such function. Therefore, you're required to display an error prompt (e.g.: "Invalid input") if the user's entry is not a number. (Hint: refer to TryParse or similar functions). MY CODE UP UNTIL NOW: Console.WriteLine("Multiplication"); Console.Write("Enter first Number: "); Int32 firstnumber = Int32.Parse(Console.ReadLine()); Console.Write("Enter Second Number: "); Int32 secondnumber = Int32.Parse(Console.ReadLine()); Console.WriteLine(firstnumber * secondnumber); Console.Write("Press any key to quit or X "); Console.ReadKey(); What should I do without having to recode the program?Explanation / Answer
Hi,
You need to use TryParse (as mentioned in the question) . It checks if input can be parsed into an integer or not. If it can , then the process continues further. Hope it helps :)
You will ahve to recode this little part if you want to solve the problem elegantly.
Console.WriteLine("Multiplication");
Console.Write("Enter first Number: ");
int firstnumber;
int secondnumber;
if (Int32.TryParse(Console.ReadLine(), out firstnumber))
{
Console.Write("Enter Second Number: ");
if (Int32.TryParse(Console.ReadLine(), out secondnumber))
{
Console.WriteLine(firstnumber * secondnumber);
Console.Write("Press any key to quit or X ");
Console.ReadKey();
}
else
{
Console.Write("Invalid input ");
}
}
else
{
Console.Write("Invalid input ");
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.