簡體   English   中英

如何在C#中轉移goto語句的控制

[英]How to transfer the control of goto statement in C#

我是編程的初學者,我正在嘗試這個獲取用戶名和排序等的簡單程序。

class Program
{
    static void Main(string[] args)
    {
        int number;
        dynamic y;

        string[] answer = new string[10];
        cases:
        Console.WriteLine("Enter the options given below 1.Add students\n 2.View all details\n 3.Sorting\n 4.Exit\n");
        int input = Convert.ToInt16(Console.ReadLine());
        switch (input)
        {
            case 1:
                Console.WriteLine("Enter the Number of Students to be added to the List");
                number = Convert.ToInt16(Console.ReadLine());
                for (int i = 0; i < number; i++)
                {
                    answer[i] = Console.ReadLine();
                }
            case 2:
                foreach (var item in answer)
                {
                    Console.WriteLine(item.ToString());
                }
                break;
            case 3:
                Array.Sort(answer);
                foreach (var item in answer)
                {
                    Console.WriteLine(item.ToString());
                }
                break;
            case 4:
                Console.WriteLine("Are you sure you want to exit");
                Console.WriteLine("1 for Yes and N for No");
                y = (char)Console.Read();
                if ((y == 1))
                {
                    goto cases;
                }
                else
                {
                    goto thankyou;
                }
                thankyou:
                Console.WriteLine("thank you");
                break;
        }
        Console.WriteLine("Are you sure you want to exit");
        Console.WriteLine("Y for Yes and 1 for No");
        y = (char)Console.Read();
        if ((y == 1))
        {
            goto cases;
        }
        else
        {
            goto thankyou;
        }
    }
}

我的問題是,每次操作后我都會問是否應該繼續。 我添加了go-to語句,但是當按下No時,它顯示了我聲明的input變量的異常。

我可以使用go-to方法嗎?或者我們有什么方法可以做到這一點? 這是我得到的例外 有什么建議嗎?

如果你想在程序中使用循環,你應該使用C#中的一個循環結構。 在這種情況下, while循環可以工作:

bool keepPrompting = true;
while(keepPrompting) {
     Console.WriteLine("Enter the options given below 1.Add students\n 2.View all details\n 3.Sorting\n 4.Exit\n");
    int input = Convert.ToInt16(Console.ReadLine());

    // The case statement on input goes here

     Console.WriteLine("Are you sure you want to exit");
     Console.WriteLine("Y for Yes and 1 for No");
     var y = (char)Console.Read();
     if (y != 'y') 
         keepPrompting = false;
}

Console.WriteLine("thank you");

goto幾乎從未在C#(或任何其他語言)中使用過,因為當循環具有已定義的流時,很難跟隨一個可以跳轉到幾乎任何位置的程序。

你不應該用goto這樣做。 你應該總是完全避免goto 如果您認為某些原因需要使用goto ,那么您應該找到一種方法來實現它而不需要goto 這是一個如何在避免goto同時執行此操作的示例。

class Program
{
    static void Main(string[] args)
    {
        int number;
        dynamic y;

        string[] answer = new string[10];
        bool result = false;
        while(!result) {

            Console.WriteLine("Enter the options given below 1.Add students\n 2.View all details\n 3.Sorting\n 4.Exit\n");
            int input = Convert.ToInt16(Console.ReadLine());
            switch (input)
            {

                case 1:
                    Console.WriteLine("Enter the Number of Students to be added to the List");
                    number = Convert.ToInt16(Console.ReadLine());

                    for (int i = 0; i < number; i++)
                    {
                        answer[i] = Console.ReadLine();
                    }
                    break;
                case 2:
                    foreach (var item in answer)
                    {
                        Console.WriteLine(item.ToString());
                    }
                    break;
                case 3:
                    Array.Sort(answer);
                    foreach (var item in answer)
                    {
                        Console.WriteLine(item.ToString());
                    }
                    break;
                case 4:
                    Console.WriteLine("Are you sure you want to exit");
                    Console.WriteLine("1 for Yes and N for No");
                    result = ((char)Console.Read()) == 'y';
                    break;
            }
        }
        Console.WriteLine("thank you");
        }
    }
}
static void Main(string[] args)
{
    // First you need a few loops, avoid goto's at all costs they make code much harder to read
    // There are better ways to do this but this will get it done
    // List<string> answer = new List<string>(); would be better here because it resizes automatically when adding
    // I left it like this because it looks like a school project
    string[] answer = new string[0]; // create variable before loops so it is not recreated on each iteration
    bool exit = false; // create bool variable and use it to exit infinite loop by setting it to true when user chooses option 4

    for (;;) // create outer infinit loop  to so the code will execute until you want you break; when option 4 is entered
    {
        int option;

        for (;;)// create infinite loop to get user input for which option they want
        {
            Console.Clear();
            Console.WriteLine("Enter the options given below\n1.Add students\n2.View all details\n3.Sorting\n4.Exit\n");
            if (int.TryParse(Console.ReadLine(), out option) && option >= 1 && option <= 4)
            { break; /*user entered valid option so we break from this infinit loop*/ }
            else
            { Console.Clear(); /*User did not enter a valid option so clear the console window*/ }
        }
        switch (option) // switch cases to handle each of the possible options entered
        {
            case 1:
                // user chose option 1
                int number = 0;
                while (number <= 0)
                {
                    Console.Clear();

                    Console.WriteLine("Enter the number of students to add.");
                    int.TryParse(Console.ReadLine(), out number);
                    answer = new string[number]; // re-initize number of students to add
                    for(int i=0;i<number;i++)
                    {
                        Console.Clear();
                        Console.WriteLine("Enter Name: ");

                        answer[i] = Console.ReadLine();
                    }
                }
                break; // break out of case 1
            case 2:
                // user chose option 2
                break;// break out of case 2
            case 3:
                // user chose option 3
                if (answer.Length > 0)
                {
                    Console.Clear();
                    Console.WriteLine("Sorted student names:");
                    Array.Sort(answer);
                    Console.WriteLine(string.Join("\n", answer));
                    Console.ReadLine(); // pause screen for reading
                }
                break;// break out of case 3
            case 4:
                // user chose option 4
                while (true) // loop until a Y or 1 is entered
                {
                    Console.WriteLine("Are you sure you want to exit\nY for YES and 1 for NO");
                    char y = (char)Console.Read();
                    if (y == 'Y' || y == 'y')
                    { exit = true; break; /*user is sure they want to exit*/ }
                    else if (y == '1')
                    { Console.Clear(); break; /*user decided not to exit*/  }
                    else
                    { Console.Clear(); }
                }
                break; // break out of case 4
        }
        if (exit) break; // if exit variable true then break out of outer infinite loop
    }
}
static void Main(string[] args)
{
    // First you need a few loops, avoid goto's at all costs they make code much harder to read
    // There are better ways to do this but this will get it done
    // List<string> answer = new List<string>(); would be better here because it resizes automatically when adding
    // I left it like this because it looks like a school project
    List<string> answer = new List<string>(); // create variable before loops so it is not recreated on each iteration
    bool exit = false; // create bool variable and use it to exit infinite loop by setting it to true when user chooses option 4

    for (;;) // create outer infinit loop  to so the code will execute until you want you break; when option 4 is entered
    {
        int option;
        for (;;)// create infinite loop to get user input for which option they want
        {
            Console.Clear();
            Console.WriteLine("Enter the options given below\n1.Add students\n2.View all details\n3.Sorting\n4.Exit\n");
            if (int.TryParse(Console.ReadLine(), out option) && option >= 1 && option <= 4)
            { break; /*user entered valid option so we break from this infinit loop*/ }
            else
            { Console.Clear(); /*User did not enter a valid option so clear the console window*/ }
        }
        switch (option) // switch cases to handle each of the possible options entered
        {
            case 1:
                // user chose option 1
                int number = 0;
                while (number <= 0)
                {
                    Console.Clear();

                    Console.WriteLine("Enter the number of students to add.");
                    int.TryParse(Console.ReadLine(), out number);
                    // Because "answer" is now a list it does not have to be sized
                    for(int i=0;i<number;i++)
                    {
                        Console.Clear();
                        Console.WriteLine("Enter Name: ");
                        // with a list, the previous list of students are not wiped out
                        // we also don't have to be carefull about writing outside array bounds because of the add method
                        answer.Add(Console.ReadLine());
                    }
                }
                break; // break out of case 1
            case 2:
                // user chose option 2
                break;// break out of case 2
            case 3:
                // user chose option 3
                if (answer.Count > 0)
                {
                    Console.Clear();
                    Console.WriteLine("Sorted student names:");
                    answer.Sort(); // List<string> have a Sort member method
                    Console.WriteLine(string.Join("\n", answer));
                }
                else
                { Console.WriteLine("No students exist to sort or list."); }

                Console.ReadLine(); // pause screen for reading
                break;// break out of case 3
            case 4:
                // user chose option 4
                while (true) // loop until a Y or 1 is entered
                {
                    Console.WriteLine("Are you sure you want to exit\nY for YES and 1 for NO");
                    char y = (char)Console.Read();
                    if (y == 'Y' || y == 'y')
                    { exit = true; break; /*user is sure they want to exit*/ }
                    else if (y == '1')
                    { Console.Clear(); break; /*user decided not to exit*/  }
                    else
                    { Console.Clear(); }
                }
                break; // break out of case 4
        }
        if (exit) break; // if exit variable true then break out of outer infinite loop
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM