PocketLuigi
PocketLuigi

Reputation: 1

How can you restart on a specific line in c#?

I'm a beginner and I tried to create a simple calculator in c#. I want that, when you finish an operation, you can restart or not. Heres my code:

    using System;

namespace Calculator
{
    class Program
    {
        static void Main(string[] args)
        {
            // First number
            Console.WriteLine("Enter a number");
                double A = Convert.ToDouble(Console.ReadLine());
            // Second number
            Console.WriteLine("Enter another number");
                double B = Convert.ToDouble(Console.ReadLine());
            // Operator
            Console.WriteLine("Enter the operator");
                string C = Console.ReadLine();
                    // if you want to add
                    if(C == "+")
                    {
                        Console.WriteLine(A + B);
                    }
                    // if you want to remove
                    if(C == "-")
                    {
                        Console.WriteLine(A - B);
                    }
                    // if you want to multiply
                    if(C == "*")
                    {
                        Console.WriteLine(A * B);
                    }
                    // if you want to subdivide
                    if(C == "/")
                    {
                        Console.WriteLine(A / B);
                    }
            // Ask if they want to restart or finish
            Console.WriteLine("Want to do another operations? y/n");
                string W = Console.ReadLine();
                    // Restart
                    if(W == "y")
                    {
                        // Return at the beginning
                    }
                    // Finish
                    if(W == "n")
                    {
                        Console.WriteLine("Enter a key to close"); 
                            Console.ReadKey();
                    }
        }
    }
}

Here you can see which, when you finish your operation, you can restart(Which is the one I don't understand how) or finish. My code (and my speech) are not efficient (I'm Italian) I'm bad at programming, I'm trying to learn by myself.

Upvotes: 0

Views: 450

Answers (1)

Gusman
Gusman

Reputation: 15161

The concrete answer to your question, how to jump to a concrete line is: goto You place a label myLabel: and then when you want to jump there you do goto myLabel;

BUT, goto is evil, it must be avoided, in a large program it makes code unreadable and leads to a ton of problems.

The good solution would be to create a loop and test for a variable, something like this:

bool execute = true;

while(execute)
{

    //..your calculator code

    Console.WriteLine("Want to do another operations? y/n");
    string W = Console.ReadLine();

    if(W == "n")
        execute = false;

}

This makes the code a lot more clean and readable.

Upvotes: 2

Related Questions