【发布时间】:2015-12-12 20:35:45
【问题描述】:
我正在为学校做一个简单的课堂项目,以试验 C# 中的继承和其他要点,但我在某个部分遇到了问题。我相信我需要在无条件的 while 循环中尝试捕获,以确保用户以正确的形式输入数据,但我还需要能够从错误处理代码中跳出循环。我在给我带来问题的代码下方添加了注释。
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 循环无法迭代命令。有人可以帮我解决这个问题吗?
【问题讨论】:
-
它确实中断了,但 for 循环将继续并再次执行 while 循环。
-
@KevinKal 它在我的屏幕上看起来不像,a 保持为 0。如果 for 循环迭代,增量不应该增加吗?
标签: c# while-loop try-catch break