C# 如果捕获到异常,请重新输入
如果出现异常,我想要求用户重新输入,但不知道如何:C# 如果捕获到异常,请重新输入,c#,exception,C#,Exception,如果出现异常,我想要求用户重新输入,但不知道如何: class Quadrilateral { Point[] pointsArr = new Point[4]; public Quadrilateral() { foreach (Point pointVar in pointsArr) { try { Console.WriteLine("Input co
class Quadrilateral
{
Point[] pointsArr = new Point[4];
public Quadrilateral()
{
foreach (Point pointVar in pointsArr)
{
try
{
Console.WriteLine("Input coordinates:");
float x = float.Parse(Console.ReadLine());
float y = float.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("Illegal value, please re-input");
}
}
}
}
我考虑使用do while循环,但有一些问题。您可以使用正常的
while
循环,并仅在没有异常的情况下递增迭代器变量,从而确保获得所需的准确输入次数。如果出现任何异常,请使用continue
关键字转到下一次迭代
为了简单起见,我使用了Int
type
int[] pointsArr = new int[4];
int arraySize = pointsArr.Length;
int i = 0;
while (i < arraySize)
{
try
{
Console.WriteLine("Input coordinates:");
float x = float.Parse(Console.ReadLine());
float y = float.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("Illegal value, please re-input");
continue;
}
i++;
}
Console.ReadLine();
int[]pointsArr=newint[4];
int arraySize=点长度;
int i=0;
而(i
您可以在循环时使用正常的,并仅在没有异常的情况下递增迭代器变量,从而确保获得所需的准确输入次数。如果出现任何异常,请使用continue
关键字转到下一次迭代
为了简单起见,我使用了Int
type
int[] pointsArr = new int[4];
int arraySize = pointsArr.Length;
int i = 0;
while (i < arraySize)
{
try
{
Console.WriteLine("Input coordinates:");
float x = float.Parse(Console.ReadLine());
float y = float.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("Illegal value, please re-input");
continue;
}
i++;
}
Console.ReadLine();
int[]pointsArr=newint[4];
int arraySize=点长度;
int i=0;
而(i