I want to ask the user if they want to continue adding two numbers, so if they type Y
it would start again if N
it will exit.
I'm not sure if I should use if
/else
or while
(or both!) or something else.
Here is what I have so far:
Console.Write("Enter a number to add: ");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter another number to add: ");
int num2 = Convert.ToInt32(Console.ReadLine());
int num3 = num1 num2;
string num11 = Convert.ToString(num1);
string num22 = Convert.ToString(num2);
Console.WriteLine(" " num1 " " num2 " = " num3);
Console.Write("Do You want to add more numbers? Y / N");
Console.ReadLine();
How can I finish it?
CodePudding user response:
while (true)
{
Console.Write("Enter a number to add: ");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter another number to add: ");
int num2 = Convert.ToInt32(Console.ReadLine());
int num3 = num1 num2;
string num11 = Convert.ToString(num1);
string num22 = Convert.ToString(num2);
Console.WriteLine(" " num1 " " num2 " = " num3);
Console.WriteLine("Do You want to add more numbers? Y / N");
string YesOrNo = Console.ReadLine();
if (YesOrNo == "N")
{
break;
}
}
You need a loop the most common that I see for a scenario like this is the while loop. You also however need a break condition so that the while loop ends an if statement is one way you could break out like in my example above. The break is reached if the user enters N into the console.
Note my example will continue to run if anything other than N is typed into the console.
CodePudding user response:
First, let's extract method ReadInt
(why should you repeat yourself?):
private static int ReadInt(string title) {
// keep asking user until correct value provided
while (true) {
if (!string.IsNullOrWhiteSpace(title))
Console.WriteLine(title);
// If we can parse user input as integer...
if (int.TryParse(Console.ReadLine(), out int result))
return result; // .. we return it
Console.WriteLine("Syntax error. Please, try again");
}
}
Main code: Here, you can wrap the code fragment into do {...} while
(since you want the loop to be performed at least once)
do {
int num1 = ReadInt("Enter a number to add: ");
int num2 = ReadInt("Enter another number to add: ");
// (long) num1 - we prevent integer overflow (if num1 and num2 are large)
Console.WriteLine($" {num1} {num2} = {(long)num1 num2}");
Console.WriteLine("Do You want to add more numbers? Y / N");
}
while(Console.ReadKey().Key == ConsoleKey.Y);