我正在为学校做一个简单的类项目,以试验 c# 中的继承和其他要素,但我在某个部分遇到了问题。我相信我需要在无条件 while 循环中 try catch 以确保用户以正确的形式输入数据,但我还需要能够从错误处理代码中跳出循环。我在给我带来问题的代码下方添加了注释。
class Program : students
{
static void Main(string[] args)
{
students stu = new students();
Console.Write("Number of students are you recording results for: ");
int studNum = int.Parse(Console.ReadLine());
stu.setNoOfStudents(studNum);
Console.WriteLine();
for (int a = 0; a < studNum; a++)
{
Console.Write("{0}. Forename: ", a + 1);
stu.setForname(Console.ReadLine());
Console.Write("{0}. Surname: ", a + 1);
stu.setSurname(Console.ReadLine());
while (0 == 0)
{
try
{
Console.Write("{0}. Age: ", a + 1);
stu.setstudentAge(int.Parse(Console.ReadLine()));
Console.Write("{0}. Percentage: ", a + 1);
stu.setpercentageMark(int.Parse(Console.ReadLine()));
stu.fillArray();
break;
// This is the block that gives me problems; the
// while loop doesn't break.
}
catch (Exception)
{
Console.WriteLine("This must be a number.");
}
}
}
}
}
我没有收到错误,因为它在 try/catch 中,但 while(0 == 0) 循环从未中断,因此 for 循环无法迭代命令。有人可以给我一个解决方案吗?
最佳答案
试试这个而不是休息
bool stop = false;
while (!stop)
{
try
{
// Time to exit the loop
stop = true;
}
catch { ... }
}
关于c# - 如何从内部的 try/catch 外部打破循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32605517/