【问题标题】:How to transfer the control of goto statement in C#如何在 C# 中转移 goto 语句的控制权
【发布时间】:2016-01-24 05:33:38
【问题描述】:

我是编程的初学者,我正在尝试这个简单的程序来获取用户名并对其进行排序等等。

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 语句,但是当按下否时,它显示我已声明的input 变量的异常。

我可以使用go-to 方法还是有什么方法可以做到这一点? 任何建议这里有什么问题?

【问题讨论】:

    标签: c# loops goto control-structure


    【解决方案1】:

    如果您想在程序中使用循环,您应该使用 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#(或任何其他语言)中使用过,因为当循环具有已定义的流程时,很难跟踪可以跳转到几乎任何位置的程序。

    【讨论】:

    • 谢谢,但if (y != "y") 显示错误。你知道这是为什么吗?
    • 它应该是 y != 'y',因为 y 是 char。我已经编辑了答案
    • 但是我遇到了一个异常。你能帮我吗@stackoverflow.com/users/161455/shf301
    • @vikram 你应该为此打开一个新问题。应该只有一个问题是一个问题。但是尝试使用 int.TryParse 来检查输入。
    【解决方案2】:

    您不应该对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");
            }
        }
    }
    

    【讨论】:

      【解决方案3】:
      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
          }
      }
      

      【讨论】:

      • 我是这个论坛的新手,当我添加文本时代码一直消失,所以我在下面添加了文本作为评论。我添加了这个块,因为对于 answer 变量, List 似乎比 string[] 更好,因为它会重新调整自身大小,让您更容易添加学生姓名。
      【解决方案4】:
      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
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多