2016-01-16 62 views
0

我有這個代碼塊下面,當我填充矩陣,如果我把錯誤輸入或空格,而不是數字,程序將停止,所以我知道它需要添加一些例外,但我不知道在哪裏或如何添加TryCatch代碼或者我應該寫在TryCatch 的身體這是什麼代碼:例外填充矩陣在C#

int row = 0; 
int col = 0; 
int[ , ] matrix1; 

row = Convert.ToInt16(Console.ReadLine()); 
col = Convert.ToInt16(Console.ReadLine()); 
matrix1 = new int[ row, col ]; 
Console.WriteLine("enter the numbers"); 
for (int i = 0; i < row; i++) 
    { 
    for (int j = 0; j < col; j++) 
     { 

     matrix1[ i, j ] = Convert.ToInt16(Console.ReadLine()); 

     } 
    } 
+0

你應該只驗證您的輸入,並以某種方式是適當的處理(如:更換爲零,或再次詢問用戶)。我不認爲有必要在這裏嘗試一下。 – CollinD

回答

0

如果你想只顯示消息並退出,那麼你可以使用

int row = 0; 
int col = 0; 
int[ , ] matrix1; 

int row = 0; 
int col = 0; 
int[ , ] matrix1; 

row = Convert.ToInt16(Console.ReadLine()); 
col = Convert.ToInt16(Console.ReadLine()); 
matrix1 = new int[ row, col ]; 
Console.WriteLine("enter the numbers"); 
try 
{ 

for (int i = 0; i < row; i++) 
{ 
    for (int j = 0; j < col; j++) 
    { 

    matrix1[ i, j ] = Convert.ToInt16(Console.ReadLine()); 

    } 
} 
} 
    catch(Exception e) 
{ 
    Console.WriteLine("You Have entered invalid character"); 


} 
+0

非常感謝! – Navid