2017-04-09 80 views
0

我想要求用户重新输入,如果有异常cathced,但不知道如何:我输入如果再次例外逮住

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循环,但有一些问题的它。

回答

2

您可以使用正常的while循环,并且只有在没有异常时才增加迭代器变量,从而确保您获得输入的确切次数。如果发生任何异常,请使用continue关键字转到下一次迭代。

我已经使用Int类型为简单起见

 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();