Reputation: 15
I've just progressed up to building a semi advanced calculator in a Console App (.NET framework) and after the task of returning the result is done, I want to just repeat all of it over again as many times as the user wants to, how would I do that?
Code that I have:
static void Main(string[] args)
{
Console.Write("Enter a number: ");
double num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter Operator (+, -, /, *) : ");
string op = Console.ReadLine();
Console.Write("Enter another number: ");
double num2 = Convert.ToDouble(Console.ReadLine());
if(op == "+")
{
Console.WriteLine(num1 + num2);
}
else if(op == "-")
{
Console.WriteLine(num1 - num2);
}
else if (op == "/")
{
Console.WriteLine(num1 / num2);
}
else if (op == "*")
{
Console.WriteLine(num1 * num2);
}
Console.ReadLine();
}
}
}
Upvotes: 0
Views: 109
Reputation: 124
Wrap everything into a while(true)
:
static void Main(string[] args)
{
while (true)
{
Console.Write("Enter a number: ");
double num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter Operator (+, -, /, *) : ");
string op = Console.ReadLine();
Console.Write("Enter another number: ");
double num2 = Convert.ToDouble(Console.ReadLine());
if(op == "+")
{
Console.WriteLine(num1 + num2);
}
else if(op == "-")
{
Console.WriteLine(num1 - num2);
}
else if (op == "/")
{
Console.WriteLine(num1 / num2);
}
else if (op == "*")
{
Console.WriteLine(num1 * num2);
}
Console.ReadLine();
}
}
You should also probably include a way for the user to exit the application without having to close the window:
Console.WriteLine("Would you like to quit? [y/n]");
if (Console.ReadLine() == "y") return;
Upvotes: 3
Reputation: 25
Use a loop? That should solve your problem. If you don't know what loops are you should research about them. They are a prime factor in all programming languages. Visit https://www.tutorialspoint.com/csharp/csharp_loops.htm for a tutorial on how to use them for your task.
Upvotes: 0