如何在C#中转移goto语句的控制
发布时间:2020-12-15 23:30:41 所属栏目:百科 来源:网络整理
导读:我是编程的初学者,我正在尝试这个获取用户名和排序等的简单程序. 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 studentsn
我是编程的初学者,我正在尝试这个获取用户名和排序等的简单程序.
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 studentsn 2.View all detailsn 3.Sortingn 4.Exitn"); 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时,它显示了我声明的输入变量的异常. 我可以使用go-to方法吗?或者我们有什么方法可以做到这一点? 解决方法
如果你想在程序中使用循环,你应该使用C#中的一个循环结构.在这种情况下,while循环可以工作:
bool keepPrompting = true; while(keepPrompting) { Console.WriteLine("Enter the options given below 1.Add studentsn 2.View all detailsn 3.Sortingn 4.Exitn"); 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#(或任何其他语言)中使用过,因为当循环具有已定义的流时,很难跟随一个可以跳转到几乎任何位置的程序. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |