Andreas24524
Andreas24524

Reputation: 19

What to use instead of "goto"-method?

I'm fairly new to programming, and I've realized that people reaaalllyy don't like "goto"-methods. I was wondering how one might write code that allows a user to decide how many entries to put in? For example, in the code below, the user inputs a name, and is then asked wether he/she wants to input another name. How could I do this without having to use go-to method?

public class GoToTest
{
    public static void Main()
    {
        InputName:
        string name;
        Console.Write("Input name: ");
        name = Console.ReadLine();

        string decision;
        Console.WriteLine(""); //Empty line for increased readability
        Console.WriteLine("Would you like to input another name? Yes - No");
        decision = Console.ReadLine();
        if (decision == "Yes")
        {
            goto InputName;
        }
        else
        {
            Console.WriteLine("Name is " + name);
        }
    }
}

Upvotes: 0

Views: 2085

Answers (3)

Andrew Morton
Andrew Morton

Reputation: 25013

You can make it tidier by checking for the exit condition like this:

string decision = "y";
while (decision == "y")
{
    string name;
    Console.Write("Input name: ");
    name = Console.ReadLine();
    Console.WriteLine("Name is " + name);
    Console.Write("\nWould you like to input another name? y/n: ");
    decision = Console.ReadLine().ToLower();
}

(\n inside a string gives you a new line.)

Or you could make it even easier on the user by letting them hit enter on its own when they have finished entering names:

string name = "x"; // anything except an empty string
Console.WriteLine("Enter a blank line to finish...");
while (!string.IsNullOrWhiteSpace(name))
{
    Console.Write("\nInput name: ");
    name = Console.ReadLine();
    if (!string.IsNullOrWhiteSpace(name))
    {
        Console.WriteLine("Name is " + name);
    }
}

I used !string.IsNullOrWhiteSpace(name) in case a user decides that a blank line means space(s) or tab(s).

Upvotes: 0

usr
usr

Reputation: 171178

A good pattern to do this is an "infinite" loop that you break off when a certain condition is met:

while (true) {
 var input = GetInputFromConsole();
 if (input == "exit")
  break;
}

The closing brace of the while loop is pretty much a goto to the top. Yet, this is better than goto because the loop provides scope for variables and visual indentation. It is easier to comprehend.

Upvotes: 5

Yogee
Yogee

Reputation: 1442

I don't like while(true) in general, So I had to give this answer.

do
{
    string name = GetName();
    Console.WriteLine("Would you like to input another name? (Y)es - (N)o");
}while(Console.ReadLine().ToUpper().StartsWith("Y"));

and GetName may look like below.

string GetName()
{
    Console.Write("Input name: ");
    return Console.ReadLine();
}

Upvotes: 1

Related Questions