2017-04-09 79 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();